// 引入Cesium库
import * as Cesium from 'cesium';
import axios from 'axios';

var dmgis = dmgis || {};
(function (dmgis) {
    // 定义枚举类型
    dmgis.enum = dmgis.enum || {};

    // 确保枚举类型是新对象，而不是引用已经存在的枚举对象
    Object.assign(dmgis.enum, {
        DMGISTileType: {
            Service: 1, //地图服务发布瓦片
            Publish: 2 //直接发布瓦片文件夹
        },
        GaodeType: {
            VEC: 1, //矢量图（含路网、含注记）
            VEC0: 2, //矢量图（含路网，不含注记）
            IMG: 3, //影像底图（不含路网，含注记）
            IMG0: 4, //影像底图（不含路网、不含注记）
            RIMG: 5, //影像路图（含路网，含注记）
            RIMG0: 6 //影像路网（含路网，不含注记）
        },
        BaiduType: {
            VEC: 1,
            IMG: 2
        },
        TiandituType: {
            VEC: 1, //矢量地图
            CVA: 2, //矢量标签
            IMG: 3, //影像地图
            CIA: 4, //影像标签
            TER: 5, //地形图
            CTA: 6 //地形标签
        }
    });

    // 对象定义
    dmgis.object = dmgis.object || {};

    // Point 类定义
    dmgis.object.Point = function (numX, numY, info) {
        this.x = numX;
        this.y = numY;
        this.info = info || null;
    };

    // Envelope 类定义
    dmgis.object.Envelope = function () {
        var self = this; // 保存this上下文
        this.minx = 8176078.237521;
        this.miny = 465041.899497;
        this.maxx = 15037685.885628;
        this.maxy = 7326649.547604;
        this.getWidth = getWidth;
        this.getCenter = getCenter;
        this.getWidth = getWidth;
        this.getHeight = getHeight;
        this.scale = scale;
        this.init = init;
        this.initenv = initenv; //初始矩形
        this.makeFromCenter = makeFromCenter;
        this.initextent = initextent;

        function getWidth() {
            return this.maxx - this.minx;
        }

        function getHeight() {
            return this.maxy - this.miny;
        }

        //缩放矩形
        function scale(factor) {
            this.makeFromCenter(this.getCenter(), this.getWidth() * factor, this.getHeight() * factor);
        }

        //得到中心点
        function getCenter() {
            var dblCenterX = this.minx + this.getWidth() / 2;
            var dblCenterY = this.miny + this.getHeight() / 2;
            return new dmgis.object.Point(dblCenterX, dblCenterY);
        }

        //中心点设置矩形
        function makeFromCenter(center, width, height) {
            this.minx = center.x - width / 2;
            this.maxx = center.x + width / 2;
            this.miny = center.y - height / 2;
            this.maxy = center.y + height / 2;
        }

        //初始矩形
        function init(env) {
            this.minx = env.minx;
            this.miny = env.miny;
            this.maxx = env.maxx;
            this.maxy = env.maxy;
        }

        function initextent(extent) {
            this.minx = extent[0];
            this.maxx = extent[2];
            this.miny = extent[1];
            this.maxy = extent[3];
        }

        //初始矩形
        function initenv(minx, miny, maxx, maxy) {
            if (minx < maxx) {
                this.minx = minx;
                this.maxx = maxx;
            } else {
                this.minx = maxx;
                this.maxx = minx;
            }
            if (miny < maxy) {
                this.miny = miny;
                this.maxy = maxy;
            } else {
                this.miny = maxy;
                this.maxy = miny;
            }
        }
    };

    dmgis.object.SpatialQuery = function () {
        this.strSql = 'dmgis_id>0'; //查询条件
        this.env = null; //查询矩形范围i  矩形和多边形只能用一个
        this.strPos = null; //查询多边形范围  子多边形之间用*号  244 244;345 345;645 543*343 321;334 765;432 321
        this.init = init;
        this.GetXmlString = GetXmlString;

        function GetXmlString() {
            var sAXLText = '<SPATIALQUERY>';
            if (this.strSql != null && this.strSql.length > 1) {
                this.strSql = this.strSql.replace('<', '%%');
                sAXLText = sAXLText + '<QUERY where="' + this.strSql + '"/>';
            }
            if (this.env != null) {
                sAXLText =
                    sAXLText +
                    '<ENVELOPE maxy="' +
                    this.env.maxy +
                    '" maxx="' +
                    this.env.maxx +
                    '" miny="' +
                    this.env.miny +
                    '" minx="' +
                    this.env.minx +
                    '"/>';
            }
            if (this.strPos != null && this.strPos.length > 1) {
                sAXLText = sAXLText + '<POLYGON coords="' + this.strPos + '"/>';
            }
            sAXLText = sAXLText + '</SPATIALQUERY>';
            return sAXLText;
        }

        function init(svr) {
            this.strSql = svr.strSql;
            this.env = null;
            if (svr.env != null) {
                this.env = new dmgis.object.Envelope();
                this.env.init(svr.env);
            }
            this.strPos = svr.strPos;
        }
    };

    dmgis.object.Chartvalue = function (lookupfield, outlineclr, outlinewid, strcolor) {
        this.lookupfield = lookupfield; //字段名
        this.outlineclr = outlineclr; //外框颜色
        this.outlinewid = outlinewid; //外框宽
        this.strcolor = strcolor; //颜色
    };

    dmgis.object.Tm = function () {
        this.type = 1; //专题图的类型 0直方图 1饼图
        this.Barkd = 20; //直方图的宽度
        this.Barhd = 10; //直方图的厚度
        this.Barfx = 0; //直方图的方向
        this.Minsize = 0;
        this.Maxsize = 50; //图屏幕的大小
        this.Minvalue = 0;
        this.Maxvalue = 500; //图显示数据的大小
        this.Transparency = 0; //是否透明 1透明 0不透明
        this.Pie = 0; //饼图是否为半圆
        this.tmFieldSet = []; //专题图字段(为Dmchartvalue数组)
        this.GetXmlString = GetXmlString; //得到xml
        this.AddTmField = AddTmField; //添加专题字段
        function GetXmlString() {
            var sAXLText = '<CHARTSYMBOL type="' + this.type + '" minsize="' + this.Minsize + '"';
            sAXLText = sAXLText + ' minvalue="' + this.Minvalue + '" maxsize="' + this.Maxsize + '"';
            sAXLText = sAXLText + ' maxvalue="' + this.Maxvalue + '" transparency="' + this.Transparency + '"';
            sAXLText =
                sAXLText +
                ' pie="' +
                this.Pie +
                '" barfx="' +
                this.Barfx +
                '" barhd="' +
                this.Barhd +
                '" barkd="' +
                this.Barkd +
                '" >';
            var num = this.tmFieldSet.length;
            for (var i = 0; i < num; i++) {
                sAXLText =
                    sAXLText +
                    '<CHARTVALUE lookupfield ="' +
                    this.tmFieldSet[i].lookupfield +
                    '" outline ="' +
                    this.tmFieldSet[i].outlineclr +
                    '" outlinewid="' +
                    this.tmFieldSet[i].outlinewid +
                    '" color="' +
                    this.tmFieldSet[i].strcolor +
                    '"  />';
            }
            sAXLText = sAXLText + '</CHARTSYMBOL>';
            return sAXLText;
        }

        function AddTmField(lookupfield, outlineclr, outlinewid, strcolor) {
            var len = this.tmFieldSet.length;
            this.tmFieldSet.push(len);
            this.tmFieldSet[len] = new dmgis.object.Chartvalue(lookupfield, outlineclr, outlinewid, strcolor);
            return true;
        }
    };

    dmgis.object.HighDisp = function () {
        this.type = 0; //高亮的类型    (3 为假，0为查询 1索 2号)
        this.isNod = 0; //高亮是否为节点
        this.strHighIndexSet = '569,562'; //高亮索引实体集合字符  1，2，3，4
        this.strHighIDSet = null; //高亮实体号集合字符   1，2，3，4
        this.sqlHigh = new dmgis.object.SpatialQuery(); //高亮的条件  SpatialQuery
        this.GetXmlString = GetXmlString;

        function GetXmlString() {
            var sAXLText = '';
            if (this.type == 0) {
                sAXLText = '<DISPHIGH type="' + this.type + '"  objtype="' + this.isNod + '">';
                sAXLText = sAXLText + this.sqlHigh.GetXmlString();
                sAXLText = sAXLText + '</DISPHIGH>';
            } else if (this.type == 1) {
                sAXLText = '<DISPHIGH type="' + this.type + '"  objtype="' + this.isNod + '">';
                sAXLText = sAXLText + '<INDEXLIST list="' + this.strHighIndexSet + '"/>';
                sAXLText = sAXLText + '</DISPHIGH>';
            } else if (this.type == 2) {
                sAXLText = '<DISPHIGH type="' + this.type + '"  objtype="' + this.isNod + '">';
                sAXLText = sAXLText + '<IDLIST list="' + this.strHighIndexSet + '"/>';
                sAXLText = sAXLText + '</DISPHIGH>';
            }

            return sAXLText;
        }
    };

    dmgis.object.Layer = function () {
        this.name = '未知'; //图层名称
        this.visible = 1; //是否可见
        this.newpath = ''; //新的文件路径  newpath只支持雷达图和影象图，影象图只支持卫星文件的修改
        this.radrangle = 230; //雷达图的公里范围
        this.hdSet = null; //高亮显示地方  HighDisp[]
        this.tmset = null; //专题图条件 Tm[]
        this.GetXmlString = GetXmlString;

        function GetXmlString() {
            var sAXLText =
                '<LAYERDEF name="' +
                this.name +
                '" radrangle="' +
                this.radrangle +
                '"  visible="' +
                '1' +
                '" newpath="' +
                this.newpath +
                '">';

            if (this.hdSet != null) {
                var num = this.hdSet.length;
                for (var i = 0; i < num; i++) {
                    sAXLText = sAXLText + this.hdSet[i].GetXmlString();
                }
            }
            if (this.tmset != null) {
                var numt = this.tmset.length;
                for (var j = 0; j < numt; j++) {
                    sAXLText = sAXLText + this.tmset[j].GetXmlString();
                }
            }
            sAXLText = sAXLText + '</LAYERDEF>';
            return sAXLText;
        }
    };

    dmgis.object.LayerDisp = function () {
        this.name = '';
        this.visible = 1;
    };

    dmgis.object.FeatureQueryParam = function () {
        this.Attribute = 1; //是否有属性
        this.BeginRecord = 0; //开始记录
        this.Envelop = 1; //是否有矩形
        this.FeatureLimit = 1000; //返回记录最大数
        this.Geometry = 1; //是否有坐标
        this.GlobalEnvelope = 1; //是否有集合的外围矩形
        this.Node = 0; //节点标志
    };

    dmgis.object.RcoVal = function () {
        this.fldname = ''; //字段名
        this.fldval = ''; //字段值
        this.fldtype = ''; //字段类型
    };

    dmgis.object.ServiceInfo = function () {
        this.serverPath = '';
        this.prjRect = null;
        this.layers = null;
    };

    dmgis.object.ImgServiceParam = function () {
        this.serverName = '世界地图'; //服务名称
        this.statesn = '-1'; //服务的密码（如果小于0为
        this.imgHig = 400; //地图宽高
        this.imgWid = 400;
        this.DispRect = new dmgis.object.Envelope(); //地图的范围
        this.layers = null; //dmgis.object.Layer[]
        this.GetXmlString = GetXmlString; //得到XML
        this.ResetService = ResetService; //通过得到的服务还原地图
        this.SetLayerVisible = SetLayerVisible; //设置一个图层显示
        this.AddLayerHDisp = AddLayerHDisp; //为一个图层添加高亮,返回高亮自己设置
        this.AddLayerTm = AddLayerTm; //为一个图层添加专题图
        this.ClearLayerHDisp = ClearLayerHDisp; //清除一个图层的高亮
        this.ClearLayerTm = ClearLayerTm; //清除一个图层的专题图
        this.SetLayerNewPath = SetLayerNewPath; //设置新的文件

        function GetXmlString() {
            var sAXLText;
            sAXLText = '<?xml version="1.0" encoding="UTF-8"?><DMGISXML version="1.1">';
            sAXLText = sAXLText + '<REQUEST>';
            sAXLText = sAXLText + '<GET_IMAGE width="' + this.imgWid + '" height="' + this.imgHig + '" ';
            sAXLText =
                sAXLText +
                'minx="' +
                this.DispRect.minx +
                '" miny="' +
                this.DispRect.miny +
                '" maxx="' +
                this.DispRect.maxx +
                '" maxy="' +
                this.DispRect.maxy +
                '" >';
            if (this.layers != null) {
                sAXLText = sAXLText + '<LAYERLIST>';
                var num = this.layers.length;
                for (var i = 0; i < num; i++) {
                    sAXLText = sAXLText + this.layers[i].GetXmlString();
                }
                sAXLText = sAXLText + '</LAYERLIST>';
            }
            sAXLText = sAXLText + '</GET_IMAGE></REQUEST></DMGISXML>';
            return sAXLText;
        }

        //还原设置  svr为DmMapServiceInfo
        function ResetService(svr) {
            if (svr == null || svr.prjRect == undefined) {
                return;
            }
            this.DispRect.minx = svr.prjRect.minx;
            this.DispRect.miny = svr.prjRect.miny;
            this.DispRect.maxx = svr.prjRect.maxx;
            this.DispRect.maxy = svr.prjRect.maxy;
            //初始化图层
            this.layers = null;
            this.layers = [];
            var num = svr.layers.length;

            for (var i = 0; i < num; i++) {
                this.layers.push(i);
                this.layers[i] = new dmgis.object.Layer();
                this.layers[i].name = svr.layers[i].name;
                this.layers[i].visible = svr.layers[i].visible;
            }
            //console.log(this.layers, '12312layers')
        }
        //设置一个图层显示
        function SetLayerVisible(layername, Is) {
            var num = this.layers.length;
            for (var i = 0; i < num; i++) {
                if (this.layers[i].name == layername) {
                    this.layers[i].visible = Is;
                    return true;
                }
            }
            return false;
        }
        //设置新的文件
        function SetLayerNewPath(layername, path, drangle) {
            var num = this.layers.length;
            for (var i = 0; i < num; i++) {
                if (this.layers[i].name == layername) {
                    this.layers[i].newpath = path;
                    if (drangle > 0) this.layers[i].radrangle = drangle;
                    return true;
                }
            }
            return false;
        }
        //为一个图层添加高亮,返回高亮自己设置
        function AddLayerHDisp(layername) {
            var num = this.layers.length;
            for (var i = 0; i < num; i++) {
                if (this.layers[i].name == layername) {
                    if (this.layers[i].hdSet == null) {
                        this.layers[i].hdSet = [];
                    }
                    var len = this.layers[i].hdSet.length;
                    this.layers[i].hdSet.push(len);

                    this.layers[i].hdSet[len] = new dmgis.object.HighDisp();

                    return this.layers[i].hdSet[len];
                }
            }
            return null;
        }
        //为一个图层添加专题图
        function AddLayerTm(layername) {
            var num = this.layers.length;
            for (var i = 0; i < num; i++) {
                if (this.layers[i].name == layername) {
                    if (this.layers[i].tmset == null) {
                        this.layers[i].tmset = []; //该图层专题图数组，存放专题图信息
                    }
                    var len = this.layers[i].tmset.length; //多个字段专题图？
                    this.layers[i].tmset.push(len);
                    this.layers[i].tmset[len] = new dmgis.object.Tm(); //专题图信息
                    return this.layers[i].tmset[len]; //返回专题图信息
                }
            }
            return null;
        }
        //清除一个图层的高亮
        function ClearLayerHDisp(layername) {
            var num = this.layers.length;
            for (var i = 0; i < num; i++) {
                if (this.layers[i].name == layername) {
                    this.layers[i].hdSet = null;
                    return true;
                }
            }
            return false;
        }
        //清除一个图层的专题图
        function ClearLayerTm(layername) {
            var num = this.layers.length;
            for (var i = 0; i < num; i++) {
                if (this.layers[i].name == layername) {
                    this.layers[i].tmset = null;
                    return true;
                }
            }
            return false;
        }
        //根据图层名称获取图层对象
        this.GetLayerByName = function (name) {
            for (var i = 0; i <= this.layers.length - 1; i++) {
                if (this.Layers[i].name == name) {
                    return this.Layers[i];
                }
            }
        };
    };

    dmgis.object.FeatureServiceParam = function () {
        this.serverName = '世界地图'; //服务名称
        this.strlayername = '行政区'; //查询的图层
        this.param = new dmgis.object.FeatureQueryParam(); //查询参数
        this.sql = new dmgis.object.SpatialQuery(); //查询条件
        this.type = 0; //查询类型0查询1索引2实体号
        this.strlist = ''; //索引号或实体号
        this.GetXmlString = GetXmlString; //得到xml
        this.SetIndexSet = SetIndexSet; //设置索引
        this.SetIdSet = SetIdSet; //设置实体

        //设置索引
        function SetIndexSet(str) {
            this.type = 1;
            this.strlist = str;
        }

        //设置实体
        function SetIdSet(str) {
            this.type = 2;
            this.strlist = str;
        }

        function GetXmlString() {
            var sAXLText;
            sAXLText = '<?xml version="1.0" encoding="UTF-8"?><DMGISXML version="1.1">';
            sAXLText = sAXLText + '<REQUEST>';
            sAXLText =
                sAXLText +
                '<GET_FEATURES  attributes="' +
                this.param.Attribute +
                '" beginrecord="' +
                this.param.BeginRecord +
                '" envelope="' +
                this.param.Envelop +
                '" featurelimit="' +
                this.param.FeatureLimit +
                '" geometry="' +
                this.param.Geometry +
                '" globalenvelope="' +
                this.param.GlobalEnvelope +
                '"';
            sAXLText = sAXLText + ' layername="' + this.strlayername + '" nodflag="' + this.param.Node + '">';
            sAXLText = sAXLText + '<GETOBJ type="' + this.type + '">';
            if (this.type == 1) {
                sAXLText = sAXLText + '<INDEXLIST list="' + this.strlist + '"/>';
            } else if (this.type == 2) {
                sAXLText = sAXLText + '<IDLIST list="' + this.strlist + '"/>';
            } else if (this.type == 0) {
                sAXLText = sAXLText + this.sql.GetXmlString();
            }
            sAXLText = sAXLText + '</GETOBJ>';
            sAXLText = sAXLText + '</GET_FEATURES>';
            sAXLText = sAXLText + '</REQUEST>';
            sAXLText = sAXLText + '</DMGISXML>';
            return sAXLText;
        }
    };

    dmgis.object.BufferServiceParam = function () {
        this.serverName = '世界地图'; //服务名称
        this.statesn = '-1'; //服务的密码（如果小于0为无态）
        this.strlayername = '行政区'; //查询的图层
        this.type = 0; //类型 0为索引1为实体号
        this.no = 0; //索引或实体号
        this.blc = 20000.0; //缓冲范围
        this.isNod = 0; //是否节点
        this.GetXmlString = GetXmlString;

        function GetXmlString() {
            var sAXLText;
            sAXLText = '<?xml version="1.0" encoding="UTF-8"?><DMGISXML version="1.1">';
            sAXLText = sAXLText + '<REQUEST>';
            sAXLText = sAXLText + '<GET_BUFFER';
            sAXLText =
                sAXLText +
                ' type="' +
                this.type +
                '" nodflag="' +
                this.isNod +
                '" layername="' +
                this.strlayername +
                '"';
            sAXLText = sAXLText + ' objindex="' + this.no + '"';
            sAXLText = sAXLText + ' bufferblc="' + this.blc + '"/>';
            sAXLText = sAXLText + '</REQUEST>';
            sAXLText = sAXLText + '</DMGISXML>';
            return sAXLText;
        }
    };

    dmgis.object.PathServiceParam = function () {
        this.serverName = '世界地图'; //服务名称
        this.statesn = '-1'; //服务的密码（如果小于0为无态）
        this.strlayername = '行政区'; //查询的图层
        this.type = 0; //类型 0点１号２索３公交
        this.ipos = '12658733.54958 3287847.75389'; //开始节点  公交ipos和epos为站点名 点为点坐标(33 44)
        this.epos = '12683917.90057 3273792.40307'; //结束节点
        this.ex = 1565.9810040136717; //路径分析误差
        this.GetXmlString = GetXmlString; //得到xml
        function GetXmlString() {
            var sAXLText;
            sAXLText = '<?xml version="1.0" encoding="UTF-8"?><DMGISXML version="1.1">';
            sAXLText = sAXLText + '<REQUEST>';
            sAXLText = sAXLText + '<GET_PATH';
            sAXLText = sAXLText + ' type="' + this.type + '" layername="' + this.strlayername + '"';
            sAXLText = sAXLText + ' ipos="' + this.ipos + '"';
            sAXLText = sAXLText + ' epos="' + this.epos + '"';
            sAXLText = sAXLText + ' wx="' + this.ex + '"/>';
            sAXLText = sAXLText + '</REQUEST>';
            sAXLText = sAXLText + '</DMGISXML>';
            return sAXLText;
        }
    };

    dmgis.object.DmRcoVal = function (fldname, fldval) {
        this.fldname = fldname;
        this.fldval = fldval;
    };

    dmgis.object.BuildServiceParam = function () {
        this.serverName = '世界地图'; //服务名称
        this.statesn = '-1'; //服务的密码（如果小于0为无态）
        this.strlayername = '主要城市'; //查询的图层
        this.type = 0; //0 为 添加实体  1为删除实体  2为修改实体图形坐标  3为修改修改属性 4为保存图层
        this.index = 0;
        this.strPos = '';
        this.rco = null; //DmRcoVal的集合
        this.GetXmlString = GetXmlString;

        function GetXmlString() {
            var sAXLText;
            sAXLText = '<?xml version="1.0" encoding="UTF-8"?><DMGISXML version="1.1">';
            sAXLText = sAXLText + '<REQUEST>';
            sAXLText = sAXLText + '<Build ';
            sAXLText =
                sAXLText +
                'type ="' +
                this.type +
                '" index="' +
                this.index +
                '" cor="' +
                this.strPos +
                '" layername="' +
                this.strlayername +
                '">';
            if (this.rco != null) {
                var num = this.rco.length;
                for (var i = 0; i < num; i++) {
                    sAXLText =
                        sAXLText + '<Field name="' + this.rco[i].fldname + '" val="' + this.rco[i].fldval + '" />';
                }
            }
            sAXLText = sAXLText + '</Build>';
            sAXLText = sAXLText + '</REQUEST>';
            sAXLText = sAXLText + '</DMGISXML>';
            return sAXLText;
        }
    };

    dmgis.object.ImageInfo = function () {
        this.imgUrl = ''; //此属性图片的网络位置
        this.imgPath = ''; //此属性图片的本地位置
        this.extent = new dmgis.object.Envelope(); //实际的地理范围
    };

    dmgis.object.WorkObj = function () {
        this.id = 0; //实体号
        this.index = 0; //索引号
        this.type = 8; //坐标类型 (0点1线面2复合体)
        this.strPnt = null; //点坐标
        this.strCor = null; //坐标 (线区和复合体线坐标）
        this.strRng = null; //坐标（复合替面坐标）
        this.env = null; //范围
        this.rec = null; //属性信息DmRcoVal集合
    };

    dmgis.object.FeatureInfo = function () {
        this.objset = null; //实体集合
        this.genv = null; //范围
        this.znum = null; //这次查询总的实体数
        this.isMore = null; //是否还有数据
    };

    dmgis.object.BufferInfo = function () {
        this.strPos = null; //缓冲的坐标
        this.env = new dmgis.object.Envelope(); //范围
    };

    dmgis.object.PathInfo = function () {
        this.strPos = ''; //坐标
        this.strSta = ''; //站点
        this.strLin = ''; //线路
        this.ll = 0; //长度
        this.env = new dmgis.object.Envelope(); //范围
    };

    dmgis.object.LengthPoint = function (_x, _y, _distance, _info) {
        this.x = _x;
        this.y = _y;
        this.Distance = _distance;
        this.info = _info || null;
    };

    dmgis.object.GridRequestPar = function (_url, _data, _success) {
        this.url = _url;
        this.data = _data;
        this.success = _success;
    };

    //工具类
    dmgis.tool = dmgis.tool ? dmgis.tool : {};
    dmgis.tool = function () {};

    dmgis.tool.Min = function (val1, val2) {
        if (val1 > val2) return val2;
        else return val1;
    };

    dmgis.tool.Max = function (val1, val2) {
        if (val1 < val2) return val2;
        else return val1;
    };

    dmgis.tool.Intersect = function (srect1, srect2) {
        var dt1 = new dmgis.object.Point(srect1.xmin, srect1.ymin);
        if (dmgis.tool.DotInRect(dt1, srect2)) return true;
        var dt2 = new dmgis.object.Point(srect1.xmin, srect1.ymax);
        if (dmgis.tool.DotInRect(dt2, srect2)) return true;
        var dt3 = new dmgis.object.Point(srect1.xmax, srect1.ymax);
        if (dmgis.tool.DotInRect(dt3, srect2)) return true;
        var dt4 = new dmgis.object.Point(srect1.xmax, srect1.ymin);
        if (dmgis.tool.DotInRect(dt4, srect2)) return true;
        return false;
    };

    dmgis.tool.DotInRect = function (pnt, rect) {
        if (pnt.x < rect.xmin) return false;
        if (pnt.x > rect.xmax) return false;
        if (pnt.y < rect.ymin) return false;
        if (pnt.y > rect.ymax) return false;
        return true;
    };

    dmgis.tool.AndRect = function (srect1, srect2) {
        var ds = new dmgis.object.Envelope();
        ds.minx = srect1.minx > srect2.minx ? srect1.minx : srect2.minx;
        ds.miny = srect1.miny > srect2.miny ? srect1.miny : srect2.miny;
        ds.maxx = srect1.maxx < srect2.maxx ? srect1.maxx : srect2.maxx;
        ds.maxy = srect1.maxy < srect2.maxy ? srect1.maxy : srect2.maxy;
        return ds;
    };

    dmgis.tool.DotInPolygon = function (PQarray, XDot, YDot) {
        var CheckFlg = false;
        var cout = 0;
        if (PQarray[PQarray.length - 1].x == XDot && PQarray[PQarray.length - 1].y == YDot) {
            CheckFlg = true;
        } else {
            if (
                (PQarray[PQarray.length - 1].y > YDot && PQarray[0].y < YDot) ||
                (PQarray[PQarray.length - 1].y < YDot && PQarray[0].y > YDot)
            ) {
                var tmpX = parseInt(
                    (PQarray[0].x * YDot +
                        PQarray[PQarray.length - 1].x * PQarray[0].y -
                        PQarray[PQarray.length - 1].x * YDot -
                        PQarray[0].x * PQarray[PQarray.length - 1].y) /
                        (PQarray[0].y - PQarray[PQarray.length - 1].y)
                );
                if (tmpX == XDot) CheckFlg = true;
                else if (tmpX > XDot) cout++;
            }
        }
        if (!CheckFlg) {
            for (var i = 0; i < PQarray.length - 1; i++) {
                if (PQarray[i].x == XDot && PQarray[i].y == YDot) {
                    CheckFlg = true;
                    break;
                } else {
                    if (
                        (PQarray[i].y > YDot && PQarray[i + 1].y < YDot) ||
                        (PQarray[i].y < YDot && PQarray[i + 1].y > YDot)
                    ) {
                        tmpX = parseInt(
                            (PQarray[i].x * YDot +
                                PQarray[i + 1].x * PQarray[i].y -
                                PQarray[i + 1].x * YDot -
                                PQarray[i].x * PQarray[i + 1].y) /
                                (PQarray[i].y - PQarray[i + 1].y)
                        );
                        if (tmpX == XDot) {
                            CheckFlg = true;
                            break;
                        } else if (tmpX > XDot) cout++;
                    }
                }
            }
        }
        if (!CheckFlg && cout % 2 == 1) CheckFlg = true;
        return CheckFlg;
    };

    dmgis.tool.GetRectCenter = function (startPoint, endPoint) {
        return new dmgis.object.Point((endPoint.x + startPoint.x) / 2, (endPoint.y + startPoint.y) / 2);
    };

    dmgis.tool.Rad = function (d) {
        return (d * Math.PI) / 180.0;
    };
    function rad(d) {
        return (d * Math.PI) / 180.0;
    }

    dmgis.tool.GetDistance = function (Point1, Point2) {
        const EARTH_RADIUS = 6378137.0;
        var radLat1 = rad(Point1.y);
        var radLat2 = rad(Point2.y);
        var a = radLat1 - radLat2;
        var b = rad(Point1.x) - rad(Point2.x);
        var s =
            2 *
            Math.asin(
                Math.sqrt(
                    Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
                )
            );
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    };

    dmgis.tool.GetLengthBy2Pnt = function (startPoint, endPoint) {
        if (startPoint.x < 180 && startPoint.x > 0) {
            return dmgis.tool.GetDistance(startPoint, endPoint);
        }
        return Math.sqrt(
            (endPoint.x - startPoint.x) * (endPoint.x - startPoint.x) +
                (endPoint.y - startPoint.y) * (endPoint.y - startPoint.y)
        );
    };

    dmgis.tool.GetLengthUnit = function (CoorLength) {
        if (CoorLength < 1000) {
            return CoorLength.toFixed(1) + '</font>米';
        } else {
            return (CoorLength / 1000).toFixed(1) + '</font>公里';
        }
    };

    dmgis.tool.GetAreaUnit = function (CoorLength) {
        if (CoorLength < 1000000) {
            return CoorLength.toFixed(1) + '</font>平方米';
        } else if (CoorLength >= 1000000 && CoorLength < 10000000000) {
            return (CoorLength / 1000000).toFixed(1) + '</font>平方公里';
        } else {
            return (CoorLength / 10000000000).toFixed(1) + '</font>万平方公里';
        }
    };

    dmgis.tool.CalculateArea = function (PointArray) {
        var area = 0;
        var i, j;
        var xjyi, xiyj;
        var xydiff;
        j = PointArray.length - 1;
        for (i = 0; i <= PointArray.length - 1; i++) {
            xiyj = PointArray[i].x * PointArray[j].y;
            xjyi = PointArray[j].x * PointArray[i].y;
            xydiff = xiyj - xjyi;
            area += xydiff;
            j = i;
        }
        area = Math.abs(area / 2);
        if (PointArray[0].x < 180 && PointArray[0].x > 0) {
            area = area * 111000 * 111000;
        }
        return area;
    };

    dmgis.tool.Rot = function (x, y, angle) {
        var a = (angle * -3.1415926) / 180;
        var ix = x * Math.cos(a) - y * Math.sin(a);
        var iy = x * Math.sin(a) + y * Math.cos(a);
        return [parseInt(ix), parseInt(iy)];
    };

    dmgis.tool.GetRectMinMax = function (pointArray) {
        var rect = new dmgis.object.Envelope();
        rect.minx = pointArray[0].x;
        rect.maxx = pointArray[0].x;
        rect.miny = pointArray[0].y;
        rect.maxy = pointArray[0].y;
        for (var i = 0; i <= pointArray.length - 1; i++) {
            if (pointArray[i].x < rect.minx) {
                rect.minx = pointArray[i].x;
            }

            if (pointArray[i].x > rect.maxx) {
                rect.maxx = pointArray[i].x;
            }

            if (pointArray[i].y < rect.miny) {
                rect.miny = pointArray[i].y;
            }

            if (pointArray[i].y > rect.maxy) {
                rect.maxy = pointArray[i].y;
            }
        }
        return rect;
    };

    dmgis.tool.Curve = function (xq, m) {
        //xq为坐标二维数组,m为已知点个数.
        var resultArray = [];
        var i,
            j,
            k = 20;
        var lx1, ly1, ly2; //曲线点坐标
        var t0, t1, t2, t3;
        lx1 = (xq[0].x + 4.0 * xq[1].x + xq[2].x) / xq.length;
        ly1 = (xq[0].y + 4.0 * xq[1].y + xq[2].y) / xq.length;
        for (i = 1; i < m - 2; i++) {
            for (j = 0; j <= k; j++) {
                t3 = (1.0 * j) / k;
                t0 = 1 - t3;
                t0 = (t0 * t0 * t0) / 6.0;
                t1 = ((3.0 * t3 - 6.0) * t3 * t3 + 4.0) / 6.0;
                t2 = (((3 - 3 * t3) * t3 + 3) * t3 + 1) / 6.0;
                t3 = 1.0 - t0 - t1 - t2;
                lx1 = xq[i - 1].x * t0 + xq[i].x * t1 + xq[i + 1].x * t2 + xq[i + 2].x * t3;
                ly1 = xq[i - 1].y * t0 + xq[i].y * t1 + xq[i + 1].y * t2 + xq[i + 2].y * t3;
                resultArray.push(new dmgis.object.Envelope(lx1, ly1));
            }
        }
        return resultArray;
    };

    dmgis.tool.CurvePnt = function (p) {
        //p为已知点,已知点有N+3个
        var q = [];
        var r = [];
        p.push(p[0]);
        p.push(p[1]);
        p.push(p[2]);
        var a = 0,
            b = 0,
            c = 0,
            d = 0,
            k = 0,
            s1 = 0,
            s2 = 0;
        var x = [];
        var y = [];
        var i, color;
        for (i = 0; i < p.length - 3; i++) {
            x[i] = p[i].x;
            y[i] = p[i].y;
            a = a + x[i];
            b = b + y[i];
        }
        a = a / (p.length - 3); //a,b 为重心 N为顶点个数
        b = b / (p.length - 3);
        c = (x[0] + 4 * x[1] + x[2]) / 6; //c,d为点X[1]Y[1]所对应的缩小点
        d = (y[0] + 4 * y[1] + y[2]) / 6;
        s1 = (x[1] - a) * (x[1] - a) + (y[1] - b) * (y[1] - b);
        s1 = Math.sqrt(s1);
        s2 = (c - a) * (c - a) + (d - b) * (d - b);
        s2 = Math.sqrt(s2);
        k = s1 / s2;
        x[p.length - 3 + 2] = (p[p.length - 3 + 2][0] + p[3].x) / 2;
        y[p.length - 3 + 2] = (p[p.length - 3 + 2][1] + p[3].y) / 2;
        for (i = 0; i < p.length - 3 + 2; i++) {
            x[i] = (p[i].x + p[i + 1].x) / 2; //x[i]y[i]为p的中点构成的多边形
            y[i] = (p[i].y + p[i + 1].y) / 2;
        }

        for (i = 0; i < p.length - 3 + 3; i++) {
            r[i] = new dmgis.object.Envelope();
            r[i].x = k * (p[i].x - a) + a;
            r[i].y = k * (p[i].y - b) + b;
        }
        return r;
    };

    dmgis.tool.ArrayToString = function (PointArray) {
        var resultStr = '';
        for (var i = 0; i <= PointArray.length - 1; i++) {
            resultStr += PointArray[i].x + ' ' + PointArray[i].y + ';';
        }
        resultStr = resultStr + PointArray[0].x + ' ' + PointArray[0].y;
        return resultStr;
    };

    dmgis.tool.StringToArray = function (strPoint) {
        var result = [];
        var row = strPoint.split(';');
        for (var i = 0; i <= row.length - 1; i++) {
            result.push(new dmgis.object.Point(parseFloat(row[i].split(' ')[0]), parseFloat(row[i].split(' ')[1])));
        }
        return result;
    };

    dmgis.tool.StringToArray2 = function (strPoint, flag) {
        var result = [];
        var row = strPoint.split(flag);
        for (var i = 0; i <= row.length - 1; i++) {
            result.push(new dmgis.object.Point(parseFloat(row[i].split(' ')[0]), parseFloat(row[i].split(' ')[1])));
        }
        return result;
    };

    dmgis.tool.transWin32ColorToHtml = function (color) {
        var htmlColor = '#ffffff';
        color = parseInt(color);
        try {
            var r = (color & 255).toString(16);
            var g = ((color >> 8) & 255).toString(16);
            var b = ((color >> 16) & 255).toString(16);
            htmlColor =
                '#' + (r.length < 2 ? '0' + r : r) + (g.length < 2 ? '0' + g : g) + (b.length < 2 ? '0' + b : b);
        } catch (e) {
            alert(e.message);
        }
        return htmlColor;
    };

    //递归获取元素的的坐标X
    dmgis.tool.getElementOffsetX = function (obj) {
        if (obj.parentNode !== null) {
            return obj.offsetLeft + dmgis.tool.getElementOffsetX(obj.parentNode);
        } else {
            if (obj.offsetLeft == undefined) {
                return 0;
            }
            return obj.offsetLeft;
        }
    };

    //递归获取元素的的坐标Y
    dmgis.tool.getElementOffsetY = function (obj) {
        if (obj.parentNode !== null) {
            return obj.offsetTop + dmgis.tool.getElementOffsetY(obj.parentNode);
        } else {
            if (obj.offsetTop == undefined) {
                return 0;
            }
            return obj.offsetTop;
        }
    };

    //获取竖向滚动条滚动数
    dmgis.tool.getBodyScrollTop = function (obj) {
        if ('pageYOffset' in window) {
            return window.pageYOffset;
        } else if (document.compatMode === 'BackCompat') {
            return document.body.scrollTop;
        } else {
            return document.documentElement.scrollTop;
        }
    };

    //获取横向滚动条滚动数
    dmgis.tool.getBodyScrollLeft = function (obj) {
        if ('pageXOffset' in window) {
            return window.pageXOffset;
        } else if (document.compatMode === 'BackCompat') {
            return document.body.scrollLeft;
        } else {
            return document.documentElement.scrollLeft;
        }
    };

    dmgis.tool.DptoSpOL = function (map, x, y) {
        var ObjCoor = [];
        ObjCoor[0] = x;
        ObjCoor[1] = y;
        var ScreenCoor = map.getPixelFromCoordinate(ObjCoor);
        var SpCoor = new dmgis.object.Point(ScreenCoor[0], ScreenCoor[1]);
        return SpCoor;
    };

    dmgis.tool.DptoSpCE = function (map, x, y) {
        var scratch = new Cesium.Cartesian2();
        var xx = parseFloat(x);
        var yy = parseFloat(y);
        try {
            if (xx == undefined || yy == undefined || isNaN(xx) || isNaN(yy)) return null;
            var position = Cesium.Cartesian3.fromDegrees(xx, yy);
            var canvasPosition = map.scene.cartesianToCanvasCoordinates(position, scratch);
            if (Cesium.defined(canvasPosition)) {
                return new dmgis.object.Point(canvasPosition.x, canvasPosition.y);
            } else {
                return null;
            }
        } catch (e) {
            // TODO: handle exception
            return null;
        }
    };

    dmgis.tool.GetWinRect = function (viewer) {
        // 范围对象
        var extent;
        let extend = viewer.camera.computeViewRectangle();
        if (typeof extend === 'undefined') {
            //2D下会可能拾取不到坐标，extend返回undefined,所以做以下转换
            let canvas = viewer.scene.canvas;
            let upperLeft = new Cesium.Cartesian2(0, 0); //canvas左上角坐标转2d坐标
            let lowerRight = new Cesium.Cartesian2(canvas.clientWidth, canvas.clientHeight); //canvas右下角坐标转2d坐标

            let ellipsoid = viewer.scene.globe.ellipsoid;
            let upperLeft3 = viewer.camera.pickEllipsoid(upperLeft, ellipsoid); //2D转3D世界坐标

            let lowerRight3 = viewer.camera.pickEllipsoid(lowerRight, ellipsoid); //2D转3D世界坐标

            let upperLeftCartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(upperLeft3); //3D世界坐标转弧度
            let lowerRightCartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(lowerRight3); //3D世界坐标转弧度

            let minx = Cesium.Math.toDegrees(upperLeftCartographic.longitude); //弧度转经纬度
            let maxx = Cesium.Math.toDegrees(lowerRightCartographic.longitude); //弧度转经纬度

            let miny = Cesium.Math.toDegrees(lowerRightCartographic.latitude); //弧度转经纬度
            let maxy = Cesium.Math.toDegrees(upperLeftCartographic.latitude); //弧度转经纬度

            console.log('经度：' + minx + '----' + maxx);
            console.log('纬度：' + miny + '----' + maxy);

            extent = new dmgis.object.Envelope();
            extent.minx = minx;
            extent.maxx = maxx;
            extent.miny = miny;
            extent.maxy = maxy;
        } else {
            //3D获取方式
            extent = new dmgis.object.Envelope();
            extent.maxx = Cesium.Math.toDegrees(extend.east);
            extent.maxy = Cesium.Math.toDegrees(extend.north);

            extent.minx = Cesium.Math.toDegrees(extend.west);
            extent.miny = Cesium.Math.toDegrees(extend.south);
        }
        return extent; //返回屏幕所在经纬度范围
    };

    dmgis.service = dmgis.service ? dmgis.service : {};
    dmgis.service = function () {};

    dmgis.service.prototype.GetServices = function (response) {
        try {
            var axlResponse = response;

            if (axlResponse.getElementsByTagName('Services').length >= 1) {
                //list = axlResponse.getElementsByTagName("Services");
                var layerList = null;
                if (axlResponse.getElementsByTagName('Service').length >= 1) {
                    layerList = axlResponse.getElementsByTagName('Service');
                    var strservice = [];
                    for (var i = 0; i < layerList.length; i++) {
                        strservice.push(i);
                        strservice[i] = layerList[i].attributes.getNamedItem('name').nodeValue;
                    }
                    return strservice;
                }
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetProjServers = function (response) {
        try {
            var axlResponse = response;
            var list = null;
            var serverInfo = null;
            if (axlResponse.getElementsByTagName('SERVER').length >= 1) {
                list = axlResponse.getElementsByTagName('SERVER');
                serverInfo = new dmgis.object.ServiceInfo();
                serverInfo.serverPath = list[0].attributes.getNamedItem('prjname').nodeValue;
                serverInfo.prjRect = new dmgis.object.Envelope();
                serverInfo.prjRect.miny = parseFloat(list[0].attributes.getNamedItem('miny').nodeValue);
                serverInfo.prjRect.minx = parseFloat(list[0].attributes.getNamedItem('minx').nodeValue);
                serverInfo.prjRect.maxx = parseFloat(list[0].attributes.getNamedItem('maxx').nodeValue);
                serverInfo.prjRect.maxy = parseFloat(list[0].attributes.getNamedItem('maxy').nodeValue);
                var layerList = null;
                if (axlResponse.getElementsByTagName('LAYER').length >= 1) {
                    layerList = axlResponse.getElementsByTagName('LAYER');
                    serverInfo.layers = [];
                    for (var i = 0; i < layerList.length; i++) {
                        serverInfo.layers.push(i);
                        serverInfo.layers[i] = new dmgis.object.LayerDisp();
                        serverInfo.layers[i].name = layerList[i].attributes.getNamedItem('name').nodeValue;
                        serverInfo.layers[i].visible = parseInt(
                            layerList[i].attributes.getNamedItem('visible').nodeValue
                        );
                    }
                }
            }
            return serverInfo;
        } catch (e) {
            alert(e);
            return null;
        }
    };

    dmgis.service.GetImageInfo = function (response) {
        try {
            var axlResponse = response;

            var inf = new dmgis.object.ImageInfo();
            if (axlResponse.getElementsByTagName('ENVELOPE').length == 1) {
                var noderefput = axlResponse.getElementsByTagName('ENVELOPE');
                inf.extent.minx = parseFloat(noderefput[0].attributes.getNamedItem('minx').nodeValue);
                inf.extent.miny = parseFloat(noderefput[0].attributes.getNamedItem('miny').nodeValue);
                inf.extent.maxx = parseFloat(noderefput[0].attributes.getNamedItem('maxx').nodeValue);
                inf.extent.maxy = parseFloat(noderefput[0].attributes.getNamedItem('maxy').nodeValue);
            }
            if (axlResponse.getElementsByTagName('OUTPUT').length == 1) {
                noderefput = axlResponse.getElementsByTagName('OUTPUT');
                inf.imgUrl = noderefput[0].attributes.getNamedItem('url').nodeValue;
                inf.imgPath = noderefput[0].attributes.getNamedItem('file').nodeValue;
                return inf;
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetFeatureInfo = function (response) {
        try {
            var axlResponse = response;

            if (axlResponse.getElementsByTagName('FEATURES').length == 1) {
                //得到实体
                var noderefput = axlResponse.getElementsByTagName('FEATURES');
                if (noderefput.length > 0) {
                    var feature = new dmgis.object.FeatureInfo();
                    //得到实体的节点
                    var node = noderefput[0];
                    //得到实体的子节点
                    var nodelist = node.childNodes;
                    var num = nodelist.length;
                    if (num > 0) {
                        //得到外围矩形

                        if (nodelist[num - 1].nodeName == 'ENVELOPE') {
                            num = num - 1;
                            feature.genv = new dmgis.object.Envelope();
                            feature.genv.minx = parseFloat(nodelist[num].attributes.getNamedItem('minx').nodeValue);
                            feature.genv.miny = parseFloat(nodelist[num].attributes.getNamedItem('miny').nodeValue);
                            feature.genv.maxx = parseFloat(nodelist[num].attributes.getNamedItem('maxx').nodeValue);
                            feature.genv.maxy = parseFloat(nodelist[num].attributes.getNamedItem('maxy').nodeValue);
                        }

                        //得到总数
                        feature.znum = parseInt(nodelist[num - 1].attributes.getNamedItem('count').nodeValue);
                        feature.isMore = parseInt(nodelist[num - 1].attributes.getNamedItem('hasmore').nodeValue);

                        num = num - 1;
                        if (num > 0) {
                            feature.objset = [];
                            for (var i = 0; i < num; i++) {
                                feature.objset.push(i);
                                feature.objset[i] = new dmgis.object.WorkObj();
                                var node1 = nodelist[i];
                                feature.objset[i].id = parseInt(node1.attributes.getNamedItem('id').nodeValue);
                                feature.objset[i].index = parseInt(node1.attributes.getNamedItem('index').nodeValue);
                                var nodelist1 = node1.childNodes;
                                for (var j = 0; j < nodelist1.length; j++) {
                                    //外围矩形
                                    if (nodelist1[j].nodeName == 'ENVELOPE') {
                                        feature.objset[i].env = new dmgis.object.Envelope();
                                        feature.objset[i].env.minx = parseFloat(
                                            nodelist1[j].attributes.getNamedItem('minx').nodeValue
                                        );
                                        feature.objset[i].env.miny = parseFloat(
                                            nodelist1[j].attributes.getNamedItem('miny').nodeValue
                                        );
                                        feature.objset[i].env.maxx = parseFloat(
                                            nodelist1[j].attributes.getNamedItem('maxx').nodeValue
                                        );
                                        feature.objset[i].env.maxy = parseFloat(
                                            nodelist1[j].attributes.getNamedItem('maxy').nodeValue
                                        );
                                    }
                                    //属性
                                    if (nodelist1[j].nodeName == 'FIELDS') {
                                        var node2 = nodelist1[j];
                                        var fnum = node2.attributes.length;
                                        feature.objset[i].rec = [];
                                        for (var z = 0; z < fnum; z++) {
                                            feature.objset[i].rec.push(z);
                                            feature.objset[i].rec[z] = new dmgis.object.RcoVal();
                                            feature.objset[i].rec[z].fldname = node2.attributes.item(z).nodeName;
                                            feature.objset[i].rec[z].fldval = node2.attributes.item(z).nodeValue;
                                        }
                                    }
                                    //坐标
                                    if (nodelist1[j].nodeName == 'POS') {
                                        var node3 = nodelist1[j];
                                        var type = parseInt(node3.attributes.getNamedItem('type').nodeValue);
                                        feature.objset[i].type = type;
                                        if (type == 0) {
                                            feature.objset[i].strPnt = node3.attributes.getNamedItem('pnt').nodeValue;
                                        } else if (type == 1) {
                                            feature.objset[i].strCor = node3.attributes.getNamedItem('cod').nodeValue;
                                        } else if (type == 2) {
                                            feature.objset[i].strPnt = node3.attributes.getNamedItem('pnt').nodeValue;
                                            feature.objset[i].strCor = node3.attributes.getNamedItem('cod').nodeValue;
                                            feature.objset[i].strRng = node3.attributes.getNamedItem('rng').nodeValue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return feature;
                }
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetBufferInfo = function (response) {
        try {
            var axlResponse = response;

            var buffer = null;
            if (axlResponse.getElementsByTagName('ENVELOPE').length == 1) {
                buffer = new dmgis.object.BufferInfo();
                var noderefput = axlResponse.getElementsByTagName('ENVELOPE');
                buffer.env.minx = parseFloat(noderefput[0].attributes.getNamedItem('minx').nodeValue);
                buffer.env.miny = parseFloat(noderefput[0].attributes.getNamedItem('miny').nodeValue);
                buffer.env.maxx = parseFloat(noderefput[0].attributes.getNamedItem('maxx').nodeValue);
                buffer.env.maxy = parseFloat(noderefput[0].attributes.getNamedItem('maxy').nodeValue);
            }
            if (axlResponse.getElementsByTagName('POLYGON').length == 1) {
                noderefput = axlResponse.getElementsByTagName('POLYGON');
                buffer.strPos = noderefput[0].attributes.getNamedItem('coords').nodeValue;
            }
            return buffer;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetPathInfo = function (response) {
        try {
            var axlResponse = response;

            var path = null;
            if (axlResponse.getElementsByTagName('ENVELOPE').length == 1) {
                path = new dmgis.object.PathInfo();
                var noderefput = axlResponse.getElementsByTagName('ENVELOPE');
                path.env.minx = parseFloat(noderefput[0].attributes.getNamedItem('minx').nodeValue);
                path.env.miny = parseFloat(noderefput[0].attributes.getNamedItem('miny').nodeValue);
                path.env.maxx = parseFloat(noderefput[0].attributes.getNamedItem('maxx').nodeValue);
                path.env.maxy = parseFloat(noderefput[0].attributes.getNamedItem('maxy').nodeValue);
            }
            if (axlResponse.getElementsByTagName('PATH').length == 1) {
                noderefput = axlResponse.getElementsByTagName('PATH');
                path.strPos = noderefput[0].attributes.getNamedItem('coords').nodeValue;
                path.ll = parseInt(noderefput[0].attributes.getNamedItem('dis').nodeValue);
                path.strLin = noderefput[0].attributes.getNamedItem('nodlist').nodeValue;
                path.strSta = noderefput[0].attributes.getNamedItem('arclist').nodeValue;
            }
            return path;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetBuildInfo = function (response) {
        try {
            var axlResponse = response;

            var builfinfo = null;
            if (axlResponse.getElementsByTagName('OBJ').length == 1) {
                builfinfo = new dmgis.object.WorkObj();
                //得到实体
                var noderefput = axlResponse.getElementsByTagName('OBJ');
                if (noderefput.length > 0) {
                    //得到实体的节点
                    var node = noderefput[0];
                    if (parseInt(node.attributes.getNamedItem('SC').nodeValue) == 1) {
                        builfinfo.index = parseInt(node.attributes.getNamedItem('index').nodeValue);
                    }
                }
                return builfinfo;
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetWMSFeatureInfo = function (response) {
        try {
            var axlResponse = response;

            if (axlResponse.getElementsByTagName('Layers').length == 1) {
                //Layers
                //得到图层
                var noderefput = axlResponse.getElementsByTagName('Layer');
                if (noderefput.length > 0) {
                    for (var k = 0; k < noderefput.length; k++) {
                        var nodelayer = noderefput[k];
                        var layerName = nodelayer.attributes.getNamedItem('name').nodeValue;
                        console.log(layerName);

                        var featurenodes = nodelayer.getElementsByTagName('Feature');

                        var feature = new dmgis.object.FeatureInfo();
                        if (featurenodes.length > 0) {
                            feature.objset = [];
                            for (var kk = 0; kk < featurenodes.length; kk++) {
                                feature.objset.push(kk);
                                feature.objset[kk] = new dmgis.object.WorkObj();
                                var featurenode = featurenodes[kk];
                                var fnum = featurenode.attributes.length;
                                feature.objset[kk].rec = [];
                                for (var z = 0; z < fnum; z++) {
                                    feature.objset[kk].rec.push(z);
                                    feature.objset[kk].rec[z] = new dmgis.object.RcoVal();
                                    feature.objset[kk].rec[z].fldname = featurenode.attributes.item(z).nodeName;
                                    feature.objset[kk].rec[z].fldval = featurenode.attributes.item(z).nodeValue;
                                }
                            }
                        }
                        return feature;
                    }
                }
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetWFSDescribeFeatureInfo = function (response) {
        try {
            var axlResponse = response;

            if (axlResponse.getElementsByTagName('xsd:schema').length == 1) {
                //xsd:schema
                var feature = new dmgis.object.FeatureInfo();

                var sequences = axlResponse.getElementsByTagName('xsd:sequence');

                var count = sequences.length;
                if (count == 1) {
                    count = 0;
                    feature.objset = [];
                    feature.objset.push(count);
                    feature.objset[count] = new dmgis.object.WorkObj();
                    feature.objset[count].rec = [];
                    //得到图层
                    var elements = sequences[0].getElementsByTagName('xsd:element');
                    if (elements.length > 0) {
                        feature.objset[count].rec = [];
                        for (var k = 0; k < elements.length; k++) {
                            var featurenode = elements[k];
                            feature.objset[count].rec.push(k);
                            feature.objset[count].rec[k] = new dmgis.object.RcoVal();
                            feature.objset[count].rec[k].fldname =
                                featurenode.attributes.getNamedItem('name').nodeValue;
                            feature.objset[count].rec[k].fldtype =
                                featurenode.attributes.getNamedItem('type').nodeValue;
                        }
                        return feature;
                    }
                }
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    dmgis.service.GetWFSTransaction = function (response) {
        try {
            var axlResponse = response;
            var buildinfo = null;
            if (axlResponse.getElementsByTagName('wfs:WFS_TransactionResponse').length == 1) {
                //xsd:schema
                var sequences = axlResponse.getElementsByTagName('wfs:TransactionResult');
                buildinfo = new dmgis.object.WorkObj();

                var num = sequences.length;
                for (var i = 0; i < num; i++) {
                    var elements = sequences[i].children; //wfs:Status
                    if (elements.length > 0) {
                        for (var k = 0; k < elements.length; k++) {
                            var featurenode = elements[k].children; //wfs:SUCCESS
                            if (featurenode.length > 0) {
                                if (featurenode[0].tagName.indexOf(':') != -1) {
                                    var rlt = featurenode[0].tagName.split(':')[1];
                                    if (rlt.indexOf('SUCCESS') != -1) {
                                        sequences = axlResponse.getElementsByTagName('wfs:InsertResult');
                                        if (sequences.length > 0) {
                                            var FeatureIds = sequences[0].children; //wfs:FeatureId
                                            if (FeatureIds.length > 0) {
                                                buildinfo.index = parseInt(
                                                    FeatureIds[0].attributes.getNamedItem('fid').nodeValue
                                                );
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return buildinfo;
            }
            return null;
        } catch (e) {
            return null;
        }
    };

    dmgis.cesiummap = dmgis.cesiummap ? dmgis.cesiummap : {};
    dmgis.cesiummap = function () {};

    dmgis.cesiummap.TileProvider = dmgis.cesiummap.TileProvider ? dmgis.cesiummap.TileProvider : {};
    dmgis.cesiummap.TileProvider = function (description, tileType) {
        var trailingSlashRegex = /\/$/;
        var defaultCredit = new Cesium.Credit('DmgisMap');
        description = Cesium.defaultValue(description, {});

        var url = Cesium.defaultValue(description.url, 'http://localhost:88/wmts');
        // if (!trailingSlashRegex.test(url)) {}
        this._url = url;
        this._format = 'image/jpg';
        this._style = 'default';
        this._hasAlphaChannel = true;
        //this._fileExtension = Cesium.defaultValue(description.fileExtension, 'png');
        this._proxy = description.proxy;
        this._tileDiscardPolicy = description.tileDiscardPolicy;
        var rectangle = Cesium.defaultValue(description.rectangle, Cesium.Rectangle.MAX_VALUE);
        this._extent = rectangle;
        this._rectangle = rectangle;
        var tilingScheme = new Cesium.GeographicTilingScheme({
            rectangle: rectangle,
            numberOfLevelZeroTilesX: 1,
            numberOfLevelZeroTilesY: 1
        });
        this._tilingScheme = tilingScheme;
        this._tileWidth = 256;
        this._tileHeight = 256;

        this._minimumLevel = Cesium.defaultValue(description.minimumLevel, 1);
        this._maximumLevel = Cesium.defaultValue(description.maximumLevel, 6);

        this._errorEvent = new Cesium.Event();
        this.iLevel = this._minimumLevel;
        this._ready = true;

        var credit = Cesium.defaultValue(description.credit, defaultCredit);
        if (typeof credit === 'string') {
            credit = new Cesium.Credit(credit);
        }
        this._credit = credit;
        this.tileType = tileType;
    };

    //这个函数需要自己实现特定地图服务的url拼接，
    function dmgisTileImageUrl(imageryProvider, x, y, level) {
        var yy = Math.pow(2, level) - y - 1;
        var xx = x;
        var url = imageryProvider._url + '/' + xx + '/' + yy + '/' + level;
        if (imageryProvider.tileType == dmgis.enum.DMGISTileType.Publish) {
            url = imageryProvider._url + '/' + level + '/' + yy + '/' + xx + '.jpg';
        }
        var proxy = imageryProvider._proxy;
        if (Cesium.defined(proxy)) {
            url = proxy.getURL(url);
        }
        return url;
    }

    Object.defineProperties(dmgis.cesiummap.TileProvider.prototype, {
        url: {
            get: function () {
                return this._url;
            }
        },

        proxy: {
            get: function () {
                return this._proxy;
            }
        },
        hasAlphaChannel: {
            get: function () {
                return this._hasAlphaChannel;
            }
        },
        tileWidth: {
            get: function () {
                if (!this._ready) {
                    throw new Cesium.DeveloperError(
                        'tileWidth must not be called before the imagery provider is ready.'
                    );
                }

                return this._tileWidth;
            }
        },

        tileHeight: {
            get: function () {
                if (!this._ready) {
                    throw new Cesium.DeveloperError(
                        'tileHeight must not be called before the imagery provider is ready.'
                    );
                }

                return this._tileHeight;
            }
        },

        maximumLevel: {
            get: function () {
                if (!this._ready) {
                    throw new Cesium.DeveloperError(
                        'maximumLevel must not be called before the imagery provider is ready.'
                    );
                }
                return this._maximumLevel;
            }
        },

        minimumLevel: {
            get: function () {
                if (!this._ready) {
                    throw new Cesium.DeveloperError(
                        'minimumLevel must not be called before the imagery provider is ready.'
                    );
                }

                return this._minimumLevel;
            }
        },

        tilingScheme: {
            get: function () {
                if (!this._ready) {
                    throw new Cesium.DeveloperError(
                        'tilingScheme must not be called before the imagery provider is ready.'
                    );
                }
                return this._tilingScheme;
            }
        },

        extent: {
            get: function () {
                if (!this._ready) {
                    throw new Cesium.DeveloperError('extent must not be called before the imagery provider is ready.');
                }
                return this._extent;
            }
        },
        rectangle: {
            get: function () {
                if (!this._ready) {
                    throw new Cesium.DeveloperError(
                        'rectangle must not be called before the imagery provider is ready.'
                    );
                }
                return this._rectangle;
            }
        },

        tileDiscardPolicy: {
            get: function () {
                if (!this._ready) {
                    throw new Cesium.DeveloperError(
                        'tileDiscardPolicy must not be called before the imagery provider is ready.'
                    );
                }
                return this._tileDiscardPolicy;
            }
        },

        errorEvent: {
            get: function () {
                return this._errorEvent;
            }
        },

        ready: {
            get: function () {
                return this._ready;
            }
        },

        credit: {
            get: function () {
                return this._credit;
            }
        }
    });

    dmgis.cesiummap.TileProvider.prototype.getTileCredits = function (x, y, level) {
        return undefined;
    };

    dmgis.cesiummap.TileProvider.prototype.requestImage = function (x, y, level) {
        if (!this._ready) {
            throw new Cesium.DeveloperError('requestImage must not be called before the imagery provider is ready.');
        }

        var url = dmgisTileImageUrl(this, x, y, level);
        return Cesium.ImageryProvider.loadImage(this, url);
    };

    dmgis.cesiummap.TileLayer = dmgis.cesiummap.TileLayer ? dmgis.cesiummap.TileLayer : {};
    dmgis.cesiummap.TileLayer = function (layerName, mapService, tileType, options) {
        if (tileType == dmgis.enum.DMGISTileType.Publish) options['url'] = mapService + '/' + layerName;
        else options['url'] = mapService + '/dts/GetDmgisTileImage/' + layerName;

        var imageryProvider = new dmgis.cesiummap.TileProvider({
            url: options.url,
            minimumLevel: options.minimumLevel ? options.minimumLevel : 1,
            maximumLevel: options.maximumLevel ? options.maximumLevel : 19,
            rectangle: Cesium.Rectangle.fromDegrees(
                options.rectangle[0],
                options.rectangle[1],
                options.rectangle[2],
                options.rectangle[3]
            )
        });

        var imageLayer = new Cesium.ImageryLayer(imageryProvider);
        return imageLayer;
    };

    //----------------高德地图----------------//
    dmgis.cesiummap.GaodeLayer = dmgis.cesiummap.GaodeLayer ? dmgis.cesiummap.GaodeLayer : {};
    dmgis.cesiummap.GaodeLayer = function (options) {
        //var options = Cesium.defaultValue(options, {});
        var maximumLevel = Cesium.defaultValue(options.maximumLevel, 16);

        var url;
        if (options.ptype == dmgis.enum.GaodeType.VEC) {
            url = 'http://wprd02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7';
        } else if (options.ptype == dmgis.enum.GaodeType.VEC0) {
            url = 'http://wprd02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=7';
        } else if (options.ptype == dmgis.enum.GaodeType.IMG) {
            url = 'http://wprd02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=6';
        } else if (options.ptype == dmgis.enum.GaodeType.IMG0) {
            url = 'http://wprd02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=6';
        } else if (options.ptype == dmgis.enum.GaodeType.RIMG) {
            url = 'http://wprd02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8';
        } else if (options.ptype == dmgis.enum.GaodeType.RIMG0) {
            url = 'http://wprd02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=8';
        }
        var imageryProvider = new Cesium.UrlTemplateImageryProvider({
            url: url,
            credit: new Cesium.Credit('高德地图服务'),
            tilingScheme: new Cesium.WebMercatorTilingScheme(),
            maximumLevel: maximumLevel
        });
        var imageLayer = new Cesium.ImageryLayer(imageryProvider);
        return imageLayer;
    };

    dmgis.cesiummap.OSMLayer = dmgis.cesiummap.OSMLayer ? dmgis.cesiummap.OSMLayer : {};
    dmgis.cesiummap.OSMLayer = function () {
        //options
        //var options = Cesium.defaultValue(options, {});
        var url = `http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`;
        var imageryProvider = new Cesium.UrlTemplateImageryProvider({
            url: url,
            credit: new Cesium.Credit('OSM地图服务'),
            subdomains: ['a', 'b', 'c'],
            tilingScheme: new Cesium.WebMercatorTilingScheme()
        });
        var imageLayer = new Cesium.ImageryLayer(imageryProvider);
        return imageLayer;
    };

    dmgis.cesiummap.TiandituLayer = dmgis.cesiummap.TiandituLayer ? dmgis.cesiummap.TiandituLayer : {};
    dmgis.cesiummap.TiandituLayer = function (layerName, options) {
        //var options = Cesium.defaultValue(options, {});

        var url;
        if (options.mapType == dmgis.enum.TiandituType.IMG) {
            url =
                'http://t1.tianditu.com/DataServer?T=img_w&x={TileCol}&y={TileRow}&l={TileMatrix}&tk=3b41248c204d6f92ca4fbd7da0386da6'; //基础影像
            //title = "基础影像";
        } else if (options.mapType == dmgis.enum.TiandituType.CIA) {
            url =
                'http://t1.tianditu.com/DataServer?T=cia_w&x={TileCol}&y={TileRow}&l={TileMatrix}&tk=3b41248c204d6f92ca4fbd7da0386da6'; //带标签影像
            //title = "基础影像标注";
        } else if (options.mapType == dmgis.enum.TiandituType.VEC) {
            url =
                'http://t1.tianditu.com/DataServer?T=vec_w&x={TileCol}&y={TileRow}&l={TileMatrix}&tk=3b41248c204d6f92ca4fbd7da0386da6'; //基础地图
            //title = "基础地图";
        } else if (options.mapType == dmgis.enum.TiandituType.CVA) {
            url =
                'http://t1.tianditu.com/DataServer?T=cva_w&x={TileCol}&y={TileRow}&l={TileMatrix}&tk=3b41248c204d6f92ca4fbd7da0386da6'; //基础地图
            //title = "基础地图标注";
        } else if (options.mapType == dmgis.enum.TiandituType.TER) {
            url =
                'http://t1.tianditu.com/DataServer?T=ter_w&x={TileCol}&y={TileRow}&l={TileMatrix}&tk=3b41248c204d6f92ca4fbd7da0386da6'; //地形图
            //title = "地形图";
        } else if (options.mapType == dmgis.enum.TiandituType.CTA) {
            url =
                'http://t1.tianditu.com/DataServer?T=cta_w&x={TileCol}&y={TileRow}&l={TileMatrix}&tk=3b41248c204d6f92ca4fbd7da0386da6'; //地形图
            //title = "地形图标注";
        }

        var imageryProvider = new Cesium.WebMapTileServiceImageryProvider({
            url: url,
            layer: layerName,
            style: 'default',
            tileMatrixSetID: 'GoogleMapsCompatible'
            // tilingScheme: new Cesium.GeographicTilingScheme()
        });
        var imageLayer = new Cesium.ImageryLayer(imageryProvider);
        return imageLayer;
    };

    dmgis.cesiummap.TileLayer = dmgis.cesiummap.TileLayer ? dmgis.cesiummap.TileLayer : {};
    dmgis.cesiummap.TileLayer = function (layerName, mapService, tileType, options) {
        if (tileType == dmgis.enum.DMGISTileType.Publish) options['url'] = mapService + '/' + layerName;
        else options['url'] = mapService + '/dts/GetDmgisTileImage/' + layerName;

        var imageryProvider = new dmgis.cesiummap.TileProvider({
            url: options.url,
            minimumLevel: options.minimumLevel ? options.minimumLevel : 1,
            maximumLevel: options.maximumLevel ? options.maximumLevel : 19,
            rectangle: Cesium.Rectangle.fromDegrees(
                options.rectangle[0],
                options.rectangle[1],
                options.rectangle[2],
                options.rectangle[3]
            )
        });

        var imageLayer = new Cesium.ImageryLayer(imageryProvider);
        return imageLayer;
    };

    dmgis.cesiummap.ServiceLayer = dmgis.cesiummap.ServiceLayer ? dmgis.cesiummap.ServiceLayer : {};
    dmgis.cesiummap.ServiceLayer = function (layerName, mapService, map, options) {
        options = options ? options : {};
        this.map = map;
        this.imageLayer = null;
        this.imgsvrParam = null;
        this.service = null;
        this.mapService = mapService;
        this.serverName = layerName;
        this.maximumLevel = options.maximumLevel ? options.maximumLevel : 18;
        this.minimumLevel = options.minimumLevel ? options.minimumLevel : 0;
        this.alpha = options.alpha ? options.alpha : 1;
        this.ImgMapService = new dmgis.object.ImgServiceParam();
    };
    dmgis.cesiummap.ServiceLayer.prototype.InitService = async function () {
        var url = this.mapService + '/dms/GetService/' + this.serverName;
        var obj = this;
        let data = null;
        try {
            // 使用 Axios 发送 get 请求
            const response = await axios.get(url);
            if (response.data == '服务请求异常!') {
                alert('服务请求异常!');
                return;
            }
            data = response.data;
            var svr = new dmgis.service.GetProjServers(response.data);
            obj.service = svr;
            obj.ImgMapService.ResetService(svr);
            obj.ImgMapService.serverName = obj.serverName;
        } catch (error) {
            alert('请求失败: ' + error.message + error.status);
        }
        return parseXMLToObjectArray(data);
    };

    dmgis.cesiummap.ServiceLayer.prototype.RefreshMap = function (ImgServiceParam) {
        var iLevel = this.map.scene.globe._surface._tilesToRender[0]._level;
        if (iLevel >= this.minimumLevel && iLevel <= this.maximumLevel) {
            this.ImgMapService = ImgServiceParam;
            if (this.ImgMapService.layers != null) {
                this.ImgMapService.imgHig = this.map.canvas.height;
                this.ImgMapService.imgWid = this.map.canvas.width;
                var extent = dmgis.tool.GetWinRect(this.map);
                console.log(this.service.prjRect);
                if (typeof extent.minx != 'undefined' && dmgis.tool.Intersect(extent, this.service.prjRect)) {
                    this.ImgMapService.DispRect.init(extent);
                    console.log(extent);
                    var url =
                        this.mapService +
                        '/dms/GetImage/' +
                        this.serverName +
                        '?param=' +
                        encodeURIComponent(this.ImgMapService.GetXmlString());

                    var rectangle = Cesium.Rectangle.fromDegrees(extent.minx, extent.miny, extent.maxx, extent.maxy);

                    var layers = this.map.scene.imageryLayers;
                    var index = -1;
                    if (this.imageLayer != null) {
                        index = layers._layers.indexOf(this.imageLayer);
                        if (index > -1) {
                            layers.remove(this.imageLayer);
                            this.imageLayer = null;
                        }
                    }
                    var imageryProvider = new Cesium.SingleTileImageryProvider({
                        url: url,
                        rectangle: rectangle
                    });
                    console.log(imageryProvider);
                    this.imageLayer = new Cesium.ImageryLayer(imageryProvider, {
                        alpha: this.alpha
                    });
                    if (index > -1) this.map.scene.imageryLayers.add(this.imageLayer, index);
                    else this.map.scene.imageryLayers.add(this.imageLayer);
                }
            }
        }
    };

    dmgis.cesiummap.ServiceLayer.prototype.UpdateFile = function (layername, newfilename) {
        this.ImgMapService.SetLayerNewPath(layername, newfilename);
        this.RefreshMap();
    };

    dmgis.cesiummap.ServiceLayer.prototype.GetImgSvrParam = function () {
        return this.ImgMapService;
    };

    dmgis.cesiummap.ServiceLayer.prototype.getLayers = function () {
        return this.service.layers;
    };

    dmgis.cesiummap.ServiceLayer.prototype.GetFeatureMapService = function (ActiveLayerName) {
        var dmFeatureMapService = new dmgis.object.FeatureServiceParam();
        dmFeatureMapService.serverName = this.ImgMapService.serverName; //服务名称
        dmFeatureMapService.strlayername = ActiveLayerName;
        return dmFeatureMapService;
    };

    dmgis.cesiummap.ServiceLayer.prototype.SendFeatureMapService = async function (svr) {
        var self = this;
        this.serviceurl = this.mapService;
        let data;
        var url =
            this.serviceurl + '/dms/GetFeature/' + svr.serverName + '?param=' + encodeURIComponent(svr.GetXmlString());
        try {
            // 使用 Axios 发送 get 请求
            const response = await axios.post(url);
            if (response.data == '服务请求异常!') {
                alert('服务请求异常!');
                return;
            }
            data = response.data;
            var dmGetFeature = new dmgis.service.GetFeatureInfo(response.data);
            //console.log(dmGetFeature);
            self.HandleFeatureInfo(dmGetFeature);
        } catch (error) {
            // alert('请求失败: ' + error.message + error.status);
        }
        return parseXMLToObjectArray(data);
    };

    dmgis.cesiummap.ServiceLayer.prototype.GetBufferMapService = function (ActiveLayerName) {
        var dmBufferMapService = new dmgis.object.BufferServiceParam();
        dmBufferMapService.serverName = this.ImgMapService.serverName; //服务名称
        dmBufferMapService.strlayername = ActiveLayerName; //查询的图层
        dmBufferMapService.type = 0; //0为索引   1为实体号
        dmBufferMapService.no = 3;
        return dmBufferMapService;
    };

    dmgis.cesiummap.ServiceLayer.prototype.SendBufferMapService = async function (svr) {
        var self = this;
        this.serviceurl = this.mapService;
        var url =
            this.serviceurl +
            '/dms/GetSpatialAnalyse/' +
            svr.serverName +
            '?param=' +
            encodeURIComponent(svr.GetXmlString());
        try {
            // 使用 Axios 发送 get 请求
            const response = await axios.get(url);
            if (response.data == '服务请求异常!') {
                alert('服务请求异常!');
                return;
            }
            var dmGetBuffer = new dmgis.service.GetBufferInfo(response.data);
            console.log(dmGetBuffer, 'getbuffer213213');
            self.HandleBufferInfo(dmGetBuffer);
        } catch (error) {
            alert('请求失败: ' + error.message + error.status);
        }
    };

    dmgis.cesiummap.ServiceLayer.prototype.GetPathMapService = function (ActiveLayerName) {
        var dmPathMapService = new dmgis.object.PathServiceParam();
        dmPathMapService.serverName = this.ImgMapService.serverName; //服务名称
        dmPathMapService.strlayername = ActiveLayerName; //查询的图层
        return dmPathMapService;
    };

    dmgis.cesiummap.ServiceLayer.prototype.SendPathMapService = async function (svr) {
        var self = this;
        this.serviceurl = this.mapService;
        var url =
            this.serviceurl +
            '/dms/GetPathAnalyse/' +
            svr.serverName +
            '?param=' +
            encodeURIComponent(svr.GetXmlString());
        try {
            // 使用 Axios 发送 get 请求
            const response = await axios.get(url);
            if (response.data == '服务请求异常!') {
                alert('服务请求异常!');
                return;
            }
            var dmGetPath = new dmgis.service.GetPathInfo(response.data);
            self.HandlePathInfo(dmGetPath);
        } catch (error) {
            alert('请求失败: ' + error.message + error.status);
        }
    };
    dmgis.cesiummap.ServiceLayer.prototype.GetBuildMapService = function (ActiveLayerName) {
        var dmBuildMapService = new dmgis.object.BuildServiceParam();
        dmBuildMapService.serverName = this.ImgMapService.serverName; //服务名称
        dmBuildMapService.strlayername = ActiveLayerName; //查询的图层
        return dmBuildMapService;
    };
    dmgis.cesiummap.ServiceLayer.prototype.SendBuildMapService = async function (svr) {
        var self = this;
        this.serviceurl = this.mapService;
        var url =
            this.serviceurl + '/dms/GetBuildMap/' + svr.serverName + '?param=' + encodeURIComponent(svr.GetXmlString());

        let data;
        try {
            // 使用 Axios 发送 请求
            const response = await axios.post(url);
            if (response.data == '服务请求异常!') {
                alert('服务请求异常!');
                return;
            }
            data = response.data;
            // var dmGetBuild = new dmgis.service.GetBuildInfo(response.data);
            // self.HandleBuildInfo(dmGetBuild);
        } catch (error) {
            alert('请求失败: ' + error.message + error.status);
        }
        return parseXMLToObjectArray(data);
    };

    //等值图
    dmgis.cesiummap.ContourLayer = dmgis.cesiummap.ContourLayer ? dmgis.cesiummap.ContourLayer : {};
    dmgis.cesiummap.ContourLayer = function (layerName, mapService, map, options) {
        this.serverName = layerName;
        options = options ? options : {};
        this.mapService = mapService;
        this.map = map;
        this.ContoursData = null;
        this.ContourExtent = options.rectangle;
        this.maximumLevel = options.maximumLevel ? options.maximumLevel : 18;
        this.minimumLevel = options.minimumLevel ? options.minimumLevel : 0;
        this.alpha = options.alpha ? options.alpha : 1;
    };
    dmgis.cesiummap.ContourLayer.prototype.UpdateContoursAtt = async function (dataurl) {
        //var self = this;
        var url =
            this.mapService +
            '/pws/CallPlugin/service' +
            '?methodName=contour&postdata=GetInterpolationWork|' +
            encodeURIComponent(dataurl);
        //var postdata = "methodName=contour&postdata=GetInterpolationWork|" + encodeURIComponent(dataurl);
        try {
            // 使用 Axios 发送 请求
            await axios.post(url).then((response) => {
                if (response.data == '服务请求异常!') {
                    alert('服务请求异常!');
                    return;
                }
                this.ContoursData = response.data;
                console.log(this, 'this123');
            });
            //return response.data;
        } catch (error) {
            alert('请求失败: ' + error.message + error.status);
        }
        console.log(this.ContoursData, 'datadzt213123123');
    };
    dmgis.cesiummap.ContourLayer.prototype.RefreshMap = function () {
        console.log(this);
        var iLevel = this.map.scene.globe._surface._tilesToRender[0]._level;
        if (iLevel >= this.minimumLevel && iLevel <= this.maximumLevel) {
            var hei = this.map.canvas.height;
            var wid = this.map.canvas.width;
            var env = dmgis.tool.GetWinRect(this.map);
            // if (!dmgis.tool.Intersect(env, this.ContourExtent))
            // 	return;
            // 	console.log(env)
            var postdata =
                this.ContoursData +
                '|' +
                this.serverName +
                '|' +
                wid +
                '|' +
                hei +
                '|' +
                env.minx +
                ',' +
                env.miny +
                ',' +
                env.maxx +
                ',' +
                env.maxy +
                '|1';
            var obj = this;
            var url = this.mapService + '/pws/CallPlugin/service';

            try {
                // 使用 Axios 发送 请求
                const response = axios.post(
                    url,
                    'methodName=contour&postdata=GetContourPic|' + encodeURIComponent(postdata)
                );
                if (response.data == '服务请求异常!') {
                    alert('服务请求异常!');
                    return;
                }
                if (response.data != null && response.data != '') {
                    console.log('33');
                    var imgurl = obj.mapService + '/res/pws/' + response.data;

                    var rectangle = Cesium.Rectangle.fromDegrees(env.minx, env.miny, env.maxx, env.maxy);
                    var layers = obj.map.scene.imageryLayers;
                    var index = -1;
                    if (obj.imageLayer != null) {
                        index = layers._layers.indexOf(obj.imageLayer);
                        if (index > -1) {
                            layers.remove(obj.imageLayer);
                            obj.imageLayer = null;
                        }
                    }
                    var imageryProvider = new Cesium.SingleTileImageryProvider({
                        url: imgurl,
                        rectangle: rectangle
                    });
                    obj.imageLayer = new Cesium.ImageryLayer(imageryProvider, {
                        alpha: obj.alpha
                    });
                    if (index > -1) obj.map.scene.imageryLayers.add(obj.imageLayer, index);
                    else obj.map.scene.imageryLayers.add(obj.imageLayer);
                }
            } catch (error) {
                alert('请求失败: ' + error.message + error.status);
            }
        }
    };

    //数据点
    dmgis.cesiummap.PointDataLayer = dmgis.cesiummap.PointDataLayer ? dmgis.cesiummap.PointDataLayer : {};
    dmgis.cesiummap.PointDataLayer = function (map, minLevel, maxLevel) {
        this.map = map;
        this.PointsArr = []; //用于保存点类信息的数组
        this.DataTemplate = null;
        this.TagTemplate = null;
        this.IsRemoveOverlay = true; //是否移除叠加图层
        this.MinLevel = minLevel;
        this.MaxLevel = maxLevel;
        this.MouseEvent = 'mouseover'; //标记所使用事件
        this.OverlayWidth = 100; //标记间隔
        this.Visible = true; //是否可见
        this.XmlHttp = null;
        this.screenCoor = [];
    };
    //清空数据
    dmgis.cesiummap.PointDataLayer.prototype.clear = function () {
        this.PointsArr = [];
        if (this.XmlHttp != null) {
            this.XmlHttp.abort();
            this.XmlHttp = null;
        }
    };
    dmgis.cesiummap.PointDataLayer.prototype.DptoSp = function (x, y) {
        var scratch = new Cesium.Cartesian2();
        var xx = parseFloat(x);
        var yy = parseFloat(y);
        try {
            if (xx == undefined || yy == undefined || isNaN(xx) || isNaN(yy)) return null;
            var position = Cesium.Cartesian3.fromDegrees(xx, yy);
            var canvasPosition = this.map.scene.cartesianToCanvasCoordinates(position, scratch);
            if (Cesium.defined(canvasPosition)) {
                return new dmgis.object.Point(canvasPosition.x, canvasPosition.y);
            } else {
                return null;
            }
        } catch (e) {
            // TODO: handle exception
            return null;
        }
    };
    //设置index
    dmgis.cesiummap.PointDataLayer.prototype.setzIndex = function (index) {
        this.el.css('zIndex', index);
    };
    dmgis.cesiummap.PointDataLayer.prototype.AddLegend = function (data, lendTitle) {
        this.mapDiv.find('#legend').remove(); //移除图例
        if (data != undefined && data.length > 0) {
            var append = '<table id="legend">';
            append += '<tr><td colspan=2 style="font-weight: bold;">' + lendTitle + '</td></tr>';
            for (var i = data.length - 1; i >= 0; i--) {
                var color = dmgis.tool.transWin32ColorToHtml(data[i].elementColor); //利用Cesium自带的color类工具进行颜色转换，并设置透明度，将rgba颜色转换从css颜色
                append +=
                    '<tr><td style="width:60px;height:32px;background-color:' +
                    color +
                    '"></td><td>' +
                    data[i].elementValue +
                    '</td></tr>';
            }
            append += '</table>';
            this.mapDiv.append(append);
        }
    };

    dmgis.cesiummap.PointDataLayer.prototype.AddSinglePoint = function (data, DataTemplate, TagTemplate, success) {
        this.PointsArr = [];
        this.removeTag();
        this.DataTemplate = DataTemplate;
        this.TagTemplate = TagTemplate;
        var DataObj = this;
        if (this.XmlHttp != null) {
            //终止jQuery的ajax请求
            this.XmlHttp.abort();
            this.XmlHttp = null;
        }
        DataObj.CacheData = data;
        DataObj.PointsArr = eval(data);
        DataObj.Draw();
        this.XmlHttp = null;
        //请求成功执行参数 success方法
        if (success != undefined) {
            success(DataObj.PointsArr);
        }
    };
    dmgis.cesiummap.PointDataLayer.prototype.AddPoint = function (url, data, DataTemplate, TagTemplate, success) {
        this.PointsArr = [];
        this.removeTag();
        this.DataTemplate = DataTemplate;
        this.TagTemplate = TagTemplate;

        if (this.XmlHttp != null) {
            //终止jQuery的ajax请求
            this.XmlHttp.abort();
            this.XmlHttp = null;
        }
        var DataObj = this;
        this.XmlHttp = function () {};
        // 使用 Axios 发送 POST 请求
        axios
            .post(url, data)
            .then((response) => {
                // 请求成功，处理响应数据
                let resultData = response.data;
                if (resultData.result && Array.isArray(resultData.result)) {
                    // 如果第一个数据是数组
                    DataObj.PointsArr =
                        resultData.result[0] instanceof Array ? resultData.result[0] : resultData.result;
                } else {
                    DataObj.PointsArr = resultData.result;
                }
                // 添加图例 图例标题 （根据实际情况添加）
                // DataObj.AddLegend(resultData[1], resultData[2]);

                DataObj.screenCoor = DataObj.Draw();

                // 请求成功执行参数 success方法
                if (success !== undefined) {
                    success(DataObj.screenCoor);
                }
            })
            .catch((error) => {
                alert('请求失败: ' + error.message + error.status);
            })
            .finally(() => {
                // 无论请求成功或失败都会执行
                this.XmlHttp = null;
            });
    };
    dmgis.cesiummap.PointDataLayer.prototype.IsInScreen = function (extent, x, y) {
        if (x < extent[0]) return false;
        if (x > extent[2]) return false;
        if (y < extent[1]) return false;
        if (y > extent[3]) return false;
        return true;
    };
    //绘制点方法
    dmgis.cesiummap.PointDataLayer.prototype.Draw = function () {
        if (this.Visible) {
            var iLevel = this.map.scene.globe._surface._tilesToRender[0]._level;
            var extent = dmgis.tool.GetWinRect(this.map);
            console.log(extent, 'fanwei21321');
            if (iLevel >= this.MinLevel && iLevel <= this.MaxLevel) {
                var TempArr = [];
                if (this.PointsArr == null) {
                    return;
                }
                for (var i = 0; i < this.PointsArr.length; i++) {
                    //遍历点集合
                    if (this.IsInScreen(extent, this.PointsArr[i].lon, this.PointsArr[i].lat)) {
                        var ScreenCoor = dmgis.tool.DptoSpCE(this.map, this.PointsArr[i].lon, this.PointsArr[i].lat);
                        if (ScreenCoor == undefined) continue;
                        var num = TempArr.length;
                        var bXjFlag = false;

                        if (this.IsRemoveOverlay) {
                            for (var j = 0; j <= num - 1; j++) {
                                if (
                                    Math.abs(ScreenCoor.x - TempArr[j].x) < this.OverlayWidth &&
                                    Math.abs(ScreenCoor.y - TempArr[j].y) < this.OverlayWidth
                                ) {
                                    bXjFlag = true;
                                    break;
                                }
                            }
                            if (bXjFlag) {
                                continue;
                            }
                        }
                        ScreenCoor.info = this.PointsArr[i];
                        TempArr.push(ScreenCoor);
                    }
                }
            }
        }
        return TempArr;
    };
    //移除标记
    dmgis.cesiummap.PointDataLayer.prototype.removeTag = function () {
        var mapDiv = this.mapDiv; // 假设 this.mapDiv 是一个 DOM 元素
        var tags = mapDiv.querySelectorAll('.tag');
        tags.forEach(function (tag) {
            tag.innerHTML = '';
        });
    };
    dmgis.cesiummap.PointDataLayer.prototype.GetInWinCoor = function (x, y) {
        return new dmgis.object.Point(
            x + dmgis.tool.getBodyScrollLeft() - dmgis.tool.getElementOffsetX(this.mapDiv[0]),
            y + dmgis.tool.getBodyScrollTop() - dmgis.tool.getElementOffsetY(this.mapDiv[0])
        );
    };
    dmgis.cesiummap.PointDataLayer.prototype.RefreshMap = function () {
        if (this.Visible) {
            var mapDiv = this.mapDiv; // 假设 this.mapDiv 是一个 DOM 元素
            var tags = mapDiv.querySelectorAll('.tag');
            tags.forEach(function (tag) {
                tag.innerHTML = '';
            });
            var iLevel = this.map.scene.globe._surface._tilesToRender[0]._level;
            if (iLevel >= this.MinLevel && iLevel <= this.MaxLevel) {
                this.Draw();
            }
        }
    };

    //网格点
    dmgis.cesiummap.GridPointDataLayer = dmgis.cesiummap.GridPointDataLayer ? dmgis.cesiummap.GridPointDataLayer : {};
    dmgis.cesiummap.GridPointDataLayer = function (map, minLevel, maxLevel) {
        this.map = map;
        this.PointsArr = []; //用于保存点类信息的数组
        this.DataTemplate = null;
        this.TagTemplate = null;
        this.IsRemoveOverlay = true; //是否移除叠加图层
        this.MinLevel = minLevel;
        this.MaxLevel = maxLevel;
        this.MouseEvent = 'mouseover'; //标记所使用事件
        this.OverlayWidth = 100; //标记间隔
        this.Visible = true; //是否可见
        this.XmlHttp = null;
        this.GridCode = ''; //网格点
        this.GridRequestPar = null;
        this.BaseLV = 5; //默认级别
        this.Extent = null;
        this.Resolution = 0;
        this.tileSize = 256;
        this.IndexList = [];
        this.screenCoor = [];
    };
    //清空数据
    dmgis.cesiummap.GridPointDataLayer.prototype.clear = function () {
        this.PointsArr = [];
        this.GridCode = '';
        this.GridRequestPar = null;
        if (this.XmlHttp != null) {
            this.XmlHttp.abort();
            this.XmlHttp = null;
        }
    };
    //设置index
    dmgis.cesiummap.GridPointDataLayer.prototype.setzIndex = function (index) {
        this.el.css('zIndex', index);
    };
    //移除标记
    dmgis.cesiummap.GridPointDataLayer.prototype.removeTag = function () {
        // 获取 this.mapDiv 内部的所有 .tag 元素
        var tags = this.mapDiv.querySelectorAll('.tag');

        // 遍历所有 .tag 元素并清空它们的 HTML 内容
        tags.forEach(function (tag) {
            tag.innerHTML = '';
        });
    };
    dmgis.cesiummap.GridPointDataLayer.prototype.GetInWinCoor = function (x, y) {
        return new dmgis.object.Point(
            x + dmgis.tool.getBodyScrollLeft() - dmgis.tool.getElementOffsetX(this.mapDiv[0]),
            y + dmgis.tool.getBodyScrollTop() - dmgis.tool.getElementOffsetY(this.mapDiv[0])
        );
    };
    dmgis.cesiummap.GridPointDataLayer.prototype.DptoSp = function (x, y) {
        return dmgis.tool.DptoSpCE(this.map, x, y);
    };
    dmgis.cesiummap.GridPointDataLayer.prototype.IsInScreen = function (extent, x, y) {
        if (x < extent[0]) return false;
        if (x > extent[2]) return false;
        if (y < extent[1]) return false;
        if (y > extent[3]) return false;
        return true;
    };

    //获取在范围内网格的索引    IndexList获取当前窗口内瓦片图层的索引
    dmgis.cesiummap.GridPointDataLayer.prototype.GetGridCode = function () {
        var winrect = dmgis.tool.GetWinRect(this.map);
        var extent = [winrect.minx, winrect.miny, winrect.maxx, winrect.maxy];
        //console.log(extent)
        var rectmap = new dmgis.object.Envelope();
        rectmap.initextent(extent);
        if (!dmgis.tool.Intersect(rectmap, this.Extent)) return;
        var dx = (this.Extent.maxx - this.Extent.minx) / Math.pow(2, this.BaseLV);
        var andrect = dmgis.tool.AndRect(rectmap, this.Extent);
        var startCol = Math.floor((andrect.minx - this.Extent.minx) / dx); //开始列
        var endCol = Math.floor((andrect.maxx - this.Extent.minx) / dx) + 1; //结束列
        var startRow = Math.floor((andrect.miny - this.Extent.miny) / dx) - 2; //开始行
        var endRow = Math.floor((andrect.maxy - this.Extent.miny) / dx) + 1 - 2; //结束行
        for (var i = startRow; i <= endRow; i++) {
            for (var j = startCol; j <= endCol; j++) {
                var code = i * this.tileSize + j;
                if (this.GridCode.indexOf('' + code) == -1) {
                    this.GridCode += code + ',';
                }
            }
        }
        //console.log(this.GridCode)
    };
    dmgis.cesiummap.GridPointDataLayer.prototype.GetResolution = function (lev) {
        // dmgis.cesiummap.GridPointDataLayer.prototype.GetResolution(lev) = function () {
        var size = Math.pow(2, lev);
        return 360 / size / this.tileSize;
    };
    //根据格网索引请求点  blv为编码网格，一般都为5;
    dmgis.cesiummap.GridPointDataLayer.prototype.AddPoint = function (blv, extent, url, data, success) {
        this.BaseLV = blv;
        this.Extent = extent;
        this.Resolution = (extent.maxx - extent.minx) / Math.pow(2, blv) / this.tileSize;
        this.GridRequestPar = new dmgis.object.GridRequestPar(url, data, success); //GridRequestPar：Grid请求参数
        this.removeTag();
        var obj = this.map;
        var DataObj = this;
        if (this.XmlHttp != null) {
            this.XmlHttp.abort();
            this.XmlHttp = null;
        }
        this.GridCode = '';
        var iLevel = this.map.scene.globe._surface._tilesToRender[0]._level;
        var res = this.GetResolution(iLevel); //当前分辨率
        if (res <= this.Resolution) {
            this.GetGridCode();
        }

        if (this.GridCode != '') {
            this.GridCode = this.GridCode.substring(0, this.GridCode.length - 1);
            this.XmlHttp = function () {};
            // 使用 Axios 发送 POST 请求
            axios
                .post(url, { param: this.GridCode })
                .then((response) => {
                    // 请求成功，处理响应数据
                    let resultData = response.data;
                    if (resultData.result == undefined) return;
                    DataObj.PointsArr = eval(resultData.result);

                    DataObj.screenCoor = DataObj.Draw();

                    if (success !== undefined) {
                        success(DataObj.screenCoor);
                    }
                })
                .catch((error) => {
                    alert('请求失败: ' + error.message + error.status);
                })
                .finally(() => {
                    // 无论请求成功或失败都会执行
                    this.XmlHttp = null;
                });
            return true;
        } else {
            return false;
        }
    };
    dmgis.cesiummap.GridPointDataLayer.prototype.Draw = function () {
        var TempArr = [];
        if (this.PointsArr == null) {
            return;
        }
        var winrect = dmgis.tool.GetWinRect(this.map);
        var extent = [winrect.minx, winrect.miny, winrect.maxx, winrect.maxy];
        for (var i = 0; i < this.PointsArr.length; i++) {
            //遍历点集合
            if (this.IsInScreen(extent, this.PointsArr[i].lon, this.PointsArr[i].lat)) {
                var ScreenCoor = dmgis.tool.DptoSpCE(this.map, this.PointsArr[i].lon, this.PointsArr[i].lat);
                if (ScreenCoor == undefined) continue;
                var num = TempArr.length;
                var bXjFlag = false;

                if (this.IsRemoveOverlay) {
                    for (var j = 0; j <= num - 1; j++) {
                        if (
                            Math.abs(ScreenCoor.x - TempArr[j].x) < this.OverlayWidth &&
                            Math.abs(ScreenCoor.y - TempArr[j].y) < this.OverlayWidth
                        ) {
                            bXjFlag = true;
                            break;
                        }
                    }
                    if (bXjFlag) {
                        continue;
                    }
                }
                var point = new dmgis.object.Point(ScreenCoor.x, ScreenCoor.y);
                point.info = this.PointsArr[i];
                TempArr.push(point);
            }
        }
        return TempArr;
    };

    //----------------地图操作基本方法----------------//
    dmgis.cesiummap.Tools = dmgis.cesiummap.Tools ? dmgis.cesiummap.Tools : {};
    // dmgis.cesiummap.Tools = function (map, _divId, _rect) {
    //     this.map3d = map;
    //     this.PrimitivesArr = [];
    //     this.mapdiv = $('#' + _divId);
    //     this.rect = _rect;

    //     var html =
    //         '<div id="toolTip" class="measure-mouse-tip" style="display:none;color:rgb(236, 159, 30);border: 1px solid rgb(236, 159, 30);position:absolute;font-size:12px;color:#fff;background-color: #a2883fab;">单击开始，双击结束</div>';
    //     $('.cesium-viewer').append(html);
    // };

    dmgis.cesiummap.Tools.prototype.flyToRectangle = function (rectangle) {
        this.map3d.camera.flyTo({
            destination: Cesium.Rectangle.fromDegrees(rectangle[0], rectangle[1], rectangle[2], rectangle[3])
        });
    };
    dmgis.cesiummap.Tools.prototype.Clear = function () {
        this.map3d.entities.removeAll();
        //移除云图 火焰 倾斜摄影 BIM 管道
        for (var obj in this.PrimitivesArr) {
            if (obj != 'border') this.map3d.scene.primitives.remove(this.PrimitivesArr[obj]);
        }
        //移除图例
        this.mapdiv.find('#legend').remove();

        //移除地下管网
        this.map3d.scene.globe.clippingPlanes = new Cesium.ClippingPlaneCollection({
            planes: [],
            edgeWidth: 1.0,
            edgeColor: Cesium.Color.WHITE.withAlpha(0.7)
        });
        //关闭地下模式
        this.map3d.scene.screenSpaceCameraController.enableCollisionDetection = true;
        this.map3d.scene.globe.translucency.enabled = false;
        this.map3d.scene.globe.depthTestAgainstTerrain = false; //会有高程遮挡效果
        //this.RefreshMap();
    };
    dmgis.cesiummap.Tools.prototype.addTools = function () {
        //创建toolbar div
        this.mapdiv.append("<div id='toolbar'></div>");
        //平移工具
        this.mapdiv.append("<div id='translation-toolbar'></div>");
        var mapobj = this.map3d;
        var map = this;
        var scene = mapobj.scene;
        var canvas = mapobj.canvas;
        canvas.setAttribute('tabindex', '0');
        canvas.onclick = function () {
            canvas.focus();
        };
        var startMousePosition;
        var mousePosition;
        var flags = {
            looking: false,
            moveForward: false,
            moveBackward: false,
            moveUp: false,
            moveDown: false,
            moveLeft: false,
            moveRight: false
        };
        var ellipsoid = scene.globe.ellipsoid;
        this.map3d.clock.onTick.addEventListener(function (clock) {
            var camera = mapobj.camera;
            if (flags.looking) {
                var width = canvas.clientWidth;
                var height = canvas.clientHeight;
                var x = (mousePosition.x - startMousePosition.x) / width;
                var y = -(mousePosition.y - startMousePosition.y) / height;
                var lookFactor = 0.05;
                camera.lookRight(x * lookFactor);
                camera.lookUp(y * lookFactor);
            }
            var cameraHeight = ellipsoid.cartesianToCartographic(camera.position).height;
            var moveRate = cameraHeight / 100.0;
            if (scene.mode == 2) {
                var tile = scene.globe._surface._tilesToRender[0];
                var level = 1;
                if (tile) {
                    level = tile._level;
                }
                moveRate = moveRate / level;
            }
            if (flags.moveForward) {
                camera.moveForward(moveRate);
            }
            if (flags.moveBackward) {
                camera.moveBackward(moveRate);
            }
            if (flags.moveUp) {
                camera.moveUp(moveRate);
            }
            if (flags.moveDown) {
                camera.moveDown(moveRate);
            }
            if (flags.moveLeft) {
                camera.moveLeft(moveRate);
            }
            if (flags.moveRight) {
                camera.moveRight(moveRate);
            }
        });

        var flagsName = null;
        var Sandcastle;
        Sandcastle.addTranslationToolbarButton(
            function () {
                flagsName = 'moveDown'; //上移
                flags[flagsName] = true;
                setTimeout(buttonEvent, 500);
            },
            function () {
                flagsName = 'moveRight'; //左移
                flags[flagsName] = true;
                setTimeout(buttonEvent, 500);
            },
            function () {
                flagsName = 'moveLeft'; //右移
                flags[flagsName] = true;
                setTimeout(buttonEvent, 500);
            },
            function () {
                flagsName = 'moveUp'; //下移
                flags[flagsName] = true;
                setTimeout(buttonEvent, 500);
            },
            'translation-toolbar'
        );
        Sandcastle.addToolbarButton('<img src="images/tool/enlarge.png">', function () {
            flagsName = 'moveForward';
            flags[flagsName] = true;
            setTimeout(buttonEvent, 500);
        });
        Sandcastle.addToolbarButton('<img src="images/tool/reduce.png">', function () {
            flagsName = 'moveBackward';
            flags[flagsName] = true;
            setTimeout(buttonEvent, 500);
        });

        function buttonEvent(flagName) {
            flags[flagsName] = false;
        }

        Sandcastle.addToolbarButton('<img src="images/tool/delete.png">', function () {
            map.Clear();
        });
        Sandcastle.addToolbarButton('<img src="images/tool/recover.png">', function () {
            setTimeout(HomeButton(map), 500);
        });
        var headingdata = 0;
        var pitchdata = -90;
        var lat = 29.68;
        Sandcastle.addToolbarButton('<img src="images/tool/left.png">', function () {
            map.map3d.camera.flyTo({
                //destination: Cesium.Rectangle.fromDegrees(map.rect[0], map.rect[1], map.rect[2], map.rect[3]),
                destination: Cesium.Cartesian3.fromDegrees(111.6, 29.68, 15000.0),
                orientation: {
                    heading: Cesium.Math.toRadians((headingdata += 5)),
                    pitch: Cesium.Math.toRadians(pitchdata),
                    roll: Cesium.Math.toRadians(0)
                }
            });
        });
        Sandcastle.addToolbarButton('<img src="images/tool/right.png">', function () {
            map.map3d.camera.flyTo({
                // destination: Cesium.Rectangle.fromDegrees(map.rect[0], map.rect[1], map.rect[2], map.rect[3]),
                destination: Cesium.Cartesian3.fromDegrees(111.6, (lat -= 0.1), 150000.0),
                orientation: {
                    heading: Cesium.Math.toRadians(headingdata),
                    pitch: Cesium.Math.toRadians((pitchdata += 5)),
                    roll: Cesium.Math.toRadians(0)
                }
            });
            console.log(
                map.map3d.camera.heading + ' 视角 ' + map.map3d.camera.pitch + ' 位置 ' + map.map3d.camera.roll
            );
        });
        //飞行
        Sandcastle.addToolbarButton('飞行', function () {
            map.map3d.camera.flyTo({
                destination: new Cesium.Cartesian3(-2767174.3598969146, 4718171.610168773, 3271781.1531445547),
                orientation: new Cesium.HeadingPitchRoll(
                    0.005622817924114898,
                    -0.3609506953857964,
                    0.00002928204511132293
                )
            });
        });

        function HomeButton(map) {
            map.flyToRectangle(map.rect);
        }
    };

    //管道 加模型
    //加高程：https://blog.csdn.net/u012425087/article/details/132401634
    dmgis.cesiummap.Tools.prototype.addPolylineVolume = async function () {
        // var cesiumTerrainProviderHeightmaps = new Cesium.CesiumTerrainProvider({
        //     url: 'http://data.mars3d.cn/terrain'
        // });
        // this.map3d.terrainProvider = cesiumTerrainProviderHeightmaps;

        this.map3d.scene.globe.depthTestAgainstTerrain = true; //开启深度测试
        var viewModel = {
            height: 0
        };
        Cesium.knockout.track(viewModel); //将视图模型对象的属性转化为监控属性

        var url = '//data.mars3d.cn/3dtiles/max-piping/tileset.json';

        async function addThreeDTiles(viewer, url, option) {
            viewer.scene.globe.depthTestAgainstTerrain = true;

            // ! 写法二：
            let tileset = {};
            if (typeof url == 'number') {
                tileset = await Cesium.Cesium3DTileset.fromIonAssetId(url, option);
            } else {
                tileset = await Cesium.Cesium3DTileset.fromUrl(url, option);
            }

            viewer.scene.primitives.add(tileset);

            return tileset; // 返回模型对象
        }

        try {
            const modelPromise = addThreeDTiles(this.map3d, url);
            modelPromise.then((tileset) => {
                this.PrimitivesArr['PolylineVolume'] = tileset;
                update3dtilesMaxtrix(tileset);
            });

            var viewer = this.map3d;

            Clippingterrain(); //地形开挖

            OpenUnderGroup(); //开启地下模式

            this.map3d.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(117.216233, 31.842759, 600)
            });
        } catch (error) {
            console.log(error);
        }

        function update3dtilesMaxtrix(tileset) {
            var params = {
                tx: 117.215502, //模型中心X轴坐标（经度，单位：十进制度）
                ty: 31.84345, //模型中心Y轴坐标（纬度，单位：十进制度）
                tz: 0, //模型中心Z轴坐标（高度，单位：米）
                rx: 0, //1,    //X轴（经度）方向旋转角度（单位：度）圆心应该是在地心，改动其中一个值的时候，不止变化了该变量，比如改动ry，模型的高度也有了显著上升
                ry: 0, //-34,    //Y轴（纬度）方向旋转角度（单位：度）
                rz: 23 //336.7     //Z轴（高程）方向旋转角度（单位：度）
            };
            //旋转
            var mx = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(params.rx));
            var my = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(params.ry));
            var mz = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(params.rz));
            var rotationX = Cesium.Matrix4.fromRotationTranslation(mx);
            var rotationY = Cesium.Matrix4.fromRotationTranslation(my);
            var rotationZ = Cesium.Matrix4.fromRotationTranslation(mz);
            //平移
            var position = Cesium.Cartesian3.fromDegrees(params.tx, params.ty, params.tz);

            var m = Cesium.Transforms.eastNorthUpToFixedFrame(position);
            //旋转、平移矩阵相乘
            Cesium.Matrix4.multiply(m, rotationX, m);
            Cesium.Matrix4.multiply(m, rotationY, m);
            Cesium.Matrix4.multiply(m, rotationZ, m);
            //赋值给tileset
            tileset._root.transform = m;
        }

        function Clippingterrain() {
            var points = [
                Cesium.Cartesian3.fromDegrees(117.214769, 31.842048, 42.63),
                Cesium.Cartesian3.fromDegrees(117.217764, 31.842048, 42.63),
                Cesium.Cartesian3.fromDegrees(117.217764, 31.843312, 42.63),
                Cesium.Cartesian3.fromDegrees(117.214769, 31.843312, 42.63)
            ];
            var pointsLength = points.length;
            var clippingPlanes = []; // 存储ClippingPlane集合
            for (var i = 0; i < pointsLength; ++i) {
                var nextIndex = (i + 1) % pointsLength;
                var midpoint = Cesium.Cartesian3.add(points[i], points[nextIndex], new Cesium.Cartesian3());
                midpoint = Cesium.Cartesian3.multiplyByScalar(midpoint, 0.5, midpoint);

                var up = Cesium.Cartesian3.normalize(midpoint, new Cesium.Cartesian3());
                var right = Cesium.Cartesian3.subtract(points[nextIndex], midpoint, new Cesium.Cartesian3());
                right = Cesium.Cartesian3.normalize(right, right);

                var normal = Cesium.Cartesian3.cross(right, up, new Cesium.Cartesian3());
                normal = Cesium.Cartesian3.normalize(normal, normal);

                var originCenteredPlane = new Cesium.Plane(normal, 0.0);
                var distance = Cesium.Plane.getPointDistance(originCenteredPlane, midpoint);
                clippingPlanes.push(new Cesium.ClippingPlane(normal, distance));
            }
            viewer.scene.globe.clippingPlanes = new Cesium.ClippingPlaneCollection({
                planes: clippingPlanes,
                edgeWidth: 1.0,
                edgeColor: Cesium.Color.WHITE.withAlpha(0.7)
            });
            var minHeight = getMinHeight(points);
            viewer.entities.add({
                polygon: {
                    hierarchy: Cesium.Cartesian3.fromDegreesArrayHeights([
                        117.214769,
                        31.842048,
                        minHeight,
                        117.217764,
                        31.842048,
                        minHeight,
                        117.217764,
                        31.843312,
                        minHeight,
                        117.214769,
                        31.843312,
                        minHeight
                    ]),
                    material: new Cesium.ImageMaterialProperty({
                        image: 'images/poly-soil.jpg'
                    }),
                    closeTop: false, // 这个要设置为false
                    extrudedHeight: 0,
                    perPositionHeight: true // 这个要设置true
                }
            });
        }

        function getMinHeight(e) {
            let minHeight = 5000000;
            let minPoint = null;
            for (let i = 0; i < e.length; i++) {
                let height = e[i]['z'];
                if (height < minHeight) {
                    minHeight = height;
                    minPoint = ellipsoidToLonLat(e[i]);
                }
            }
            return minPoint.altitude;
        }

        function ellipsoidToLonLat(c) {
            let ellipsoid = viewer.scene.globe.ellipsoid;
            let cartesian3 = new Cesium.Cartesian3(c.x, c.y, c.z);
            let cartographic = ellipsoid.cartesianToCartographic(cartesian3);
            let lat = Cesium.Math.toDegrees(cartographic.latitude);
            let lng = Cesium.Math.toDegrees(cartographic.longitude);
            let alt = cartographic.height;
            return {
                longitude: lng,
                latitude: lat,
                altitude: alt
            };
        }

        function OpenUnderGroup() {
            //设置鼠标进去地下
            viewer.scene.screenSpaceCameraController.enableCollisionDetection = false;
            //设置地球透明
            viewer.scene.globe.translucency.enabled = true;
            viewer.scene.globe.translucency.frontFaceAlphaByDistance = new Cesium.NearFarScalar(400.0, 0.5, 8000, 0.9);
        }

        function CloseUnderGroud() {
            viewer.scene.screenSpaceCameraController.enableCollisionDetection = true;
            viewer.scene.globe.translucency.enabled = false;
        }
    };

    //****************************测量空间面积************************************************//
    dmgis.cesiummap.Tools.prototype.measureArea = function () {
        var viewer = this.map3d;
        var positions = [];
        var tempPoints = [];
        var polygon = null;
        var ellipsoid = viewer.scene.globe.ellipsoid;
        var billboards = new Cesium.BillboardCollection();
        viewer.scene.primitives.add(billboards);
        var billboard = undefined;
        var tooltip = document.getElementById('toolTip');
        tooltip.innerHTML = '<span>单击开始,右键结束</span>';
        //隐藏选中容器标识
        var element = document.querySelector('.cesium-selection-wrapper');
        if (element) {
            element.style.display = 'none';
        }
        // var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene._imageryLayerCollection);
        var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
        handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        var cartesian = null;
        var floatingPoints = []; //浮动点
        var floatingPoint; //浮动点
        tooltip.style.display = 'block';
        var tempLabelCollection = new Cesium.LabelCollection();
        var measureDisplayLabel = tempLabelCollection.add({
            fillColor: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.BLACK,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            font: '13px sans-serif',
            verticalOrigin: Cesium.VerticalOrigin.TOP
        });
        viewer.scene.primitives.add(tempLabelCollection);
        this.PrimitivesArr['measureArea'] = tempLabelCollection;

        handler.setInputAction(function (movement) {
            tooltip.style.left = movement.endPosition.x + 3 + 'px';
            tooltip.style.top = movement.endPosition.y - 25 + 'px';
            tooltip.style.display = 'block';
            if (positions.length < 2) {
                return;
            }
            let ray = viewer.camera.getPickRay(movement.endPosition);
            cartesian = viewer.scene.globe.pick(ray, viewer.scene);
            positions.pop(); //移除最后一个
            positions.push(cartesian);
            if (positions.length >= 2) {
                var dynamicPositions = new Cesium.CallbackProperty(function () {
                    return new Cesium.PolygonHierarchy(positions);
                }, false);
                polygon = PolygonPrimitive(dynamicPositions);
                // if (positions.length > 2) {
                var label = String(countAreaInCartesian3(positions));
                label = label.substr(0, label.indexOf('.', 0));
                var text;
                if (label.length < 6) text = label + '平方米';
                else {
                    label = String(label / 1000000);
                    label = label.substr(0, label.indexOf('.', 0) + 3);
                    text = label + '平方公里';
                }
                measureDisplayLabel.text = text;
                measureDisplayLabel.position = countCenter(positions);
                tooltip.innerHTML = '<p>右键确定终点</p>';
                // }
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        handler.setInputAction(function (movement) {
            let ray = viewer.camera.getPickRay(movement.position);
            cartesian = viewer.scene.globe.pick(ray, viewer.scene);
            if (positions.length == 0) {
                positions.push(cartesian.clone());
            }
            positions.push(cartesian);
            //在三维场景中添加点
            var cartographic = Cesium.Cartographic.fromCartesian(positions[positions.length - 1]);
            var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
            var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
            var heightString = cartographic.height;
            tempPoints.push({ lon: longitudeString, lat: latitudeString, hei: heightString });
            floatingPoint = viewer.entities.add({
                name: '多边形面积',
                position: positions[positions.length - 1],
                point: {
                    show: true,
                    color: Cesium.Color.SKYBLUE,
                    pixelSize: 3,
                    outlineColor: Cesium.Color.YELLOW,
                    outlineWidth: 1,
                    heightReference: Cesium.HeightReference.none
                }
            });
            floatingPoints.push(floatingPoint);
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        handler.setInputAction(function (movement) {
            handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
            handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
            // handler.destroy(); //关闭事件句柄
            positions.pop(); //最后一个点无效
            viewer.trackedEntity = undefined;
            billboard = billboards.add({
                show: true,
                id: 'measureTool',
                position: positions[positions.length - 1],
                pixelOffset: new Cesium.Cartesian2(0.0, 20),
                eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.CENTER,
                scale: 1.0,
                image: './images/img/close.png',
                color: new Cesium.Color(1.0, 1.0, 1.0, 1.0)
            });
            //关闭按钮执行事件
            handler.setInputAction(function (event) {
                var pickedObjects = {};
                pickedObjects = viewer.scene.drillPick(event.position);
                if (Cesium.defined(pickedObjects)) {
                    for (var i = 0; i < pickedObjects.length; i++)
                        if (pickedObjects[i].primitive == billboard) {
                            viewer.entities.remove(polygon); //清除多边形
                            for (var j = 0; j < tempPoints.length; j++) {
                                //清除点
                                viewer.entities.remove(tempPoints[j]);
                            }
                            for (var k = 0; k < floatingPoints.length; k++) {
                                //清除点
                                viewer.entities.remove(floatingPoints[k]);
                            }
                            tempPoints = [];
                            billboards.remove(billboard);
                            tempLabelCollection.remove(measureDisplayLabel);
                            positions = [];
                            polygon = undefined;
                            handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
                        }
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
            tooltip.style.display = 'none';
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

        function PolygonPrimitive(positions) {
            polygon = viewer.entities.add({
                polygon: {
                    hierarchy: positions,
                    material: Cesium.Color.ORANGE.withAlpha(0.5)
                }
            });
            return polygon;
        }

        var countCenter = function (ps) {
            var x = 0;
            var y = 0;
            var z = 0;
            for (var j = 0; j < ps.length; j++) {
                x += ps[j].x;
                y += ps[j].y;
                z += ps[j].z;
            }
            var center = new Cesium.Cartesian3(x / ps.length, y / ps.length, z / ps.length);
            return center;
        };
        var countAreaInCartesian3 = function (pointsold) {
            var points = new Array(pointsold.length);
            for (var i = 0; i < pointsold.length; i++) {
                points[i] = PItoDU(ellipsoid.cartesianToCartographic(pointsold[i]));
            }
            var center = 0;
            for (var j = 0; j < points.length; j++) center += points[j].longitude;
            center = center / points.length;
            for (var k = 0; k < points.length; k++) {
                points[k] = GASProjection.Gauss_to_XY(points[k].longitude, points[k].latitude, center);
            }
            return Math.abs(countArea(points));
        };
        var PItoDU = function (location) {
            location.longitude = (location.longitude / Math.PI) * 180;
            location.latitude = (location.latitude / Math.PI) * 180;
            return location;
        };
        var countArea = function (ps) {
            var s = 0;
            for (var i = 0; i < ps.length; i++) {
                var p1 = ps[i];
                var p2;
                if (i < ps.length - 1) p2 = ps[i + 1];
                else p2 = ps[0];
                s += p1.x * p2.y - p2.x * p1.y;
            }
            return s / 2;
        };
    };
    //画线
    var CreatePolyline1 = (function () {
        function _(positons, cesium) {
            if (!Cesium.defined(positons)) {
                throw new Cesium.DeveloperError('positions is required!');
            }
            if (positons.length < 2) {
                throw new Cesium.DeveloperError('positions 的长度必须大于等于2');
            }
            var material = Cesium.Material.fromType(Cesium.Material.ColorType);
            material.uniforms.color = new Cesium.Color(1.0, 1.0, 0.0, 0.5);
            this.options = {
                polyline: {
                    show: true,
                    width: 4,
                    material: new Cesium.PolylineOutlineMaterialProperty({
                        color: Cesium.Color.ORANGE.withAlpha(0.5),
                        outlineWidth: 0,
                        outlineColor: Cesium.Color.ORANGE
                    }),
                    depthFailMaterial: new Cesium.PolylineOutlineMaterialProperty({
                        color: Cesium.Color.RED,
                        outlineWidth: 1,
                        outlineColor: Cesium.Color.RED
                    }),
                    followSurface: true
                }
            };
            this.path = positons;

            this._init(cesium);
        }

        _.prototype._init = function (cesium) {
            var that = this;
            var positionCBP = function () {
                return that.path;
            };
            this.options.polyline.positions = new Cesium.CallbackProperty(positionCBP, false);
            this.lineEntity = cesium.map3d.entities.add(this.options);
        };

        return _;
    })();
    //测量距离
    dmgis.cesiummap.Tools.prototype.measureDistance = function () {
        var isDraw = false;
        var polylinePath = [];
        var polylineCartographic = []; //弧度数组,地表插值用
        var polyline = undefined;
        var scene = this.map3d.scene;
        var dmgismap = this;
        var ellipsoid = scene.globe.ellipsoid;
        var billboards = new Cesium.BillboardCollection();
        scene.primitives.add(billboards);
        var WebMercatorProjection = new Cesium.WebMercatorProjection();
        var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
        var tooltip = document.getElementById('toolTip');
        tooltip.innerHTML = '<span>单击开始,双击结束</span>';
        var entities = [];
        var billboard = undefined;
        //隐藏选中容器标识
        var element = document.querySelector('.cesium-selection-wrapper');
        if (element) {
            element.style.display = 'none';
        }
        handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
        handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
        isDraw = true;
        //scene.globe.depthTestAgainstTerrain = true;
        handler.setInputAction(function (movement) {
            //var cartesian = this.map3d.camera.pickEllipsoid(movement.endPosition, ellipsoid);
            //新增部分
            var position1;
            var cartographic;
            var ray = dmgismap.map3d.scene.camera.getPickRay(movement.endPosition);
            if (ray) position1 = dmgismap.map3d.scene.globe.pick(ray, dmgismap.map3d.scene);
            if (position1) cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position1);
            //世界坐标转地理坐标（弧度）
            // var cartographic = dmgismap.map3d.scene.globe.ellipsoid.cartesianToCartographic(cartesian);
            if (cartographic) {
                //海拔
                var height = dmgismap.map3d.scene.globe.getHeight(cartographic);
                //地理坐标（弧度）转经纬度坐标
                var point = Cesium.Cartesian3.fromDegrees(
                    (cartographic.longitude / Math.PI) * 180,
                    (cartographic.latitude / Math.PI) * 180,
                    height
                );
                //var point = Cesium.Cartesian3.fromDegrees(currentLon, currentLat, height);
                if (isDraw) {
                    tooltip.style.left = movement.endPosition.x + 10 + 'px';
                    tooltip.style.top = movement.endPosition.y + 20 + 'px';
                    tooltip.style.display = 'block';
                    if (polylinePath.length < 1) {
                        return;
                    }
                    if (!Cesium.defined(polyline)) {
                        polylinePath.push(point);
                        polyline = new CreatePolyline1(polylinePath, dmgismap);
                    } else {
                        polyline.path.pop();
                        polyline.path.push(point);
                    }
                    if (polylinePath.length >= 1) {
                        if (polyline && polyline.path) {
                            var distance = getDistance(polyline.path);
                            tooltip.innerHTML = '<p>长度：' + distance + '</p><p>双击确定终点</p>';
                        }
                    }
                }
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        //线段之间地表插值
        var SurfaceLine = function (cartographic) {
            polylineCartographic.push(cartographic);
            var terrainSamplePositions = [];
            if (polylineCartographic.length > 1) {
                var p1 = polylineCartographic[polylineCartographic.length - 2];
                var p2 = polylineCartographic[polylineCartographic.length - 1];
                var a = Math.abs(p1.longitude - p2.longitude) * 10000000;
                var b = Math.abs(p1.latitude - p2.latitude) * 10000000;
                if (a > b) b = a;
                var length = parseInt(b / 10);
                if (length > 1000) length = 1000;
                if (length < 2) length = 2;
                for (var i = 0; i < length; ++i) {
                    terrainSamplePositions.push(
                        new Cesium.Cartographic(
                            Cesium.Math.lerp(p1.longitude, p2.longitude, i / (length - 1)),
                            Cesium.Math.lerp(p1.latitude, p2.latitude, i / (length - 1))
                        )
                    );
                }
            } else {
                terrainSamplePositions = polylineCartographic;
            }
            if (terrainSamplePositions.length > 0) {
                for (var j = 0; j < terrainSamplePositions.length; j++) {
                    //地理坐标（弧度）转经纬度坐标
                    cartographic = terrainSamplePositions[j];
                    var height = dmgismap.map3d.scene.globe.getHeight(cartographic);
                    var point = Cesium.Cartesian3.fromDegrees(
                        (cartographic.longitude / Math.PI) * 180,
                        (cartographic.latitude / Math.PI) * 180,
                        height
                    );
                    polylinePath.push(point);
                    //console.log(point);
                }
            }
        };

        //左键画点
        handler.setInputAction(function (event) {
            //var cartesian = dmgismap.map3d.camera.pickEllipsoid(movement.position, ellipsoid);
            //新增部分
            //dmgismap.map3d.scene.globe.depthTestAgainstTerrain = true;
            var position1;
            var cartographic;
            var ray = dmgismap.map3d.scene.camera.getPickRay(event.position);
            if (ray) position1 = dmgismap.map3d.scene.globe.pick(ray, dmgismap.map3d.scene);
            if (position1) cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position1);
            //世界坐标转地理坐标（弧度）
            //var cartographic = dmgismap.map3d.scene.globe.ellipsoid.cartesianToCartographic(cartesian);
            if (cartographic) {
                //海拔
                var height = dmgismap.map3d.scene.globe.getHeight(cartographic);
                //地理坐标（弧度）转经纬度坐标
                var point = Cesium.Cartesian3.fromDegrees(
                    (cartographic.longitude / Math.PI) * 180,
                    (cartographic.latitude / Math.PI) * 180,
                    height
                );
                // var point = Cesium.Cartesian3.fromDegrees(currentLon,currentLat,height);
                if (isDraw) {
                    //polylinePath.push(cartographic);
                    //polylinePath.push(point);
                    if (polyline) polyline.path.pop();
                    SurfaceLine(cartographic);
                    var text = '起点';
                    if (polyline) {
                        text = getDistance(polyline.path);
                    }
                    entities.push(
                        dmgismap.map3d.entities.add({
                            position: point,
                            point: {
                                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                                show: true,
                                color: Cesium.Color.SKYBLUE,
                                pixelSize: 3,
                                outlineColor: Cesium.Color.YELLOW,
                                outlineWidth: 1
                            },
                            label: {
                                text: text,
                                font: '12px sans-serif',
                                style: Cesium.LabelStyle.FILL,
                                outlineWidth: 1,
                                showBackground: true, //显示背景
                                backgroundColor: Cesium.Color.WHITE, //背景色
                                backgroundPadding: new Cesium.Cartesian2(5, 5), //padding值
                                fillColor: Cesium.Color.RED,
                                //showBackground: false,
                                //backgroundColor: Cesium.Color.ORANGE.withAlpha(0.6),
                                horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                                pixelOffset: new Cesium.Cartesian2(5.0, -20.0)
                            }
                        })
                    );
                }
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        //双击结束事件
        handler.setInputAction(function () {
            handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
            handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
            //handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
            //dmgismap.map3d.zoomTo(polyline.lineEntity);
            dmgismap.map3d.trackedEntity = undefined;
            isDraw = false;
            //dmgismap.map3d.scene.globe.depthTestAgainstTerrain = false;
            billboard = billboards.add({
                show: true,
                id: 'measureTool',
                position: polylinePath[polylinePath.length - 1],
                pixelOffset: new Cesium.Cartesian2(0.0, 20),
                eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.CENTER,
                scale: 1.0,
                image: './images/img/close.png',
                color: new Cesium.Color(1.0, 1.0, 1.0, 1.0)
            });

            tooltip.style.display = 'none';
            //关闭按钮执行事件
            handler.setInputAction(function (event) {
                var pickedObjects = {};
                pickedObjects = scene.drillPick(event.position);
                if (Cesium.defined(pickedObjects)) {
                    for (var i = 0; i < pickedObjects.length; i++)
                        if (pickedObjects[i].primitive == billboard) {
                            dmgismap.map3d.entities.remove(polyline.lineEntity);
                            for (var j = 0; j < entities.length; j++) {
                                dmgismap.map3d.entities.remove(entities[j]);
                            }
                            entities = [];
                            billboards.remove(billboard);
                            polylinePath = [];
                            polyline = undefined;
                            handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
                        }
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
        //}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        //获取线段距离
        var getDistance = function (path) {
            var Len = 0;
            var distance = 0 + '米';
            var cg, cs, x1, y1, x2, y2;
            for (var i = 0; i < path.length - 1; i += 1) {
                cg = ellipsoid.cartesianToCartographic(path[i]);
                cs = WebMercatorProjection.project(cg);
                x1 = cs.x;
                y1 = cs.y;
                cg = ellipsoid.cartesianToCartographic(path[i + 1]);
                cs = WebMercatorProjection.project(cg);
                x2 = cs.x;
                y2 = cs.y;
                Len = Len + Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
            }
            if (Len > 0) {
                distance = Len.toFixed(2) + '米';
            }
            if (Len / 1000 >= 1) {
                distance = (Len / 1000).toFixed(2) + '公里';
            }
            return distance;
        };
    };

    //绘制矩形
    dmgis.cesiummap.Tools.prototype.drawRectangle = function (sucess) {
        var handler = new Cesium.ScreenSpaceEventHandler(this.map3d.scene.canvas);
        handler.destroy();
        /**
         * 矩形四点坐标
         */
        let westSouthEastNorth = [];
        /**实体的唯一标注 */
        let id = null;
        /**地图点击对象 */
        handler = new Cesium.ScreenSpaceEventHandler(this.map3d.scene.canvas);
        handler.setInputAction((click) => {
            /**点击位置笛卡尔坐标 */
            let cartesian = this.map3d.camera.pickEllipsoid(click.position, this.map3d.scene.globe.ellipsoid);
            /**笛卡尔转弧度坐标 */
            let cartographic = Cesium.Cartographic.fromCartesian(
                cartesian,
                this.map3d.scene.globe.ellipsoid,
                new Cesium.Cartographic()
            );
            /**点击位置经度 */
            let lng1 = Cesium.Math.toDegrees(cartographic.longitude);
            /**点击位置维度 */
            let lat1 = Cesium.Math.toDegrees(cartographic.latitude);
            /**边框坐标 */
            westSouthEastNorth = [lng1, lat1];
            id = new Date().getTime();
            if (westSouthEastNorth) {
                handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
            }
            /**面实例对象 */
            let polygons = this.map3d.entities.add({
                name: 'rectangle',
                id: id,
                polygon: {
                    hierarchy: new Cesium.CallbackProperty(function () {
                        return {
                            positions: Cesium.Cartesian3.fromDegreesArray(westSouthEastNorth)
                        };
                    }, false),
                    height: 0,
                    // 填充的颜色，withAlpha透明度
                    material: Cesium.Color.RED.withAlpha(0.2),
                    // 是否被提供的材质填充
                    fill: true,
                    // 是否显示
                    show: true
                },
                polyline: {
                    positions: new Cesium.CallbackProperty(function () {
                        return Cesium.Cartesian3.fromDegreesArray(westSouthEastNorth);
                    }, false),
                    material: Cesium.Color.ORANGE.withAlpha(0.5),
                    width: 1,
                    zIndex: 1
                }
            });
            handler.setInputAction((move) => {
                let cartesian = this.map3d.camera.pickEllipsoid(move.endPosition, this.map3d.scene.globe.ellipsoid);
                let cartographic = Cesium.Cartographic.fromCartesian(
                    cartesian,
                    this.map3d.scene.globe.ellipsoid,
                    new Cesium.Cartographic()
                );
                let lng = Cesium.Math.toDegrees(cartographic.longitude);
                let lat = Cesium.Math.toDegrees(cartographic.latitude);

                westSouthEastNorth = [lng1, lat1, lng1, lat, lng, lat, lng, lat1, lng1, lat1];
            }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        handler.setInputAction(() => {
            handler.destroy();
            console.log(westSouthEastNorth);
            sucess(westSouthEastNorth);
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    };
    dmgis.cesiummap.Tools.prototype.drawPlane = function (sucess) {
        var handler = new Cesium.ScreenSpaceEventHandler(this.map3d.scene.canvas);
        handler.destroy();
        /**实体的唯一标注 */
        let id = new Date().getTime();
        /**记录拐点坐标 */
        let positions = [],
            /**记录返回结果 */
            codeArrInfo = [],
            /**记录返回结果 */
            codeInfo = [],
            /**面的hierarchy属性 */
            polygon = new Cesium.PolygonHierarchy(),
            _polygonEntity = new Cesium.Entity(),
            /**面对象配置 */
            polyObj = null;
        handler = new Cesium.ScreenSpaceEventHandler(this.map3d.scene.canvas);
        // left
        handler.setInputAction((movement) => {
            let cartesian = this.map3d.camera.pickEllipsoid(movement.position, this.map3d.scene.globe.ellipsoid);
            let cartographic = Cesium.Cartographic.fromCartesian(
                cartesian,
                this.map3d.scene.globe.ellipsoid,
                new Cesium.Cartographic()
            );
            let lng = Cesium.Math.toDegrees(cartographic.longitude);
            let lat = Cesium.Math.toDegrees(cartographic.latitude);

            if (cartesian && cartesian.x) {
                if (positions.length == 0) {
                    positions.push(cartesian.clone());
                }
                codeInfo.push([lng, lat]);
                codeArrInfo.push(lng);
                codeArrInfo.push(lat);
                positions.push(cartesian.clone());
                polygon.positions.push(cartesian.clone());
                if (!polyObj) {
                    _polygonEntity.polyline = {
                        width: 1,
                        material: Cesium.Color.ORANGE.withAlpha(0.5),
                        clampToGround: false
                    };
                    _polygonEntity.polyline.positions = new Cesium.CallbackProperty(function () {
                        return positions;
                    }, false);

                    _polygonEntity.polygon = {
                        hierarchy: new Cesium.CallbackProperty(function () {
                            return polygon;
                        }, false),

                        material: Cesium.Color.ORANGE.withAlpha(0.2),
                        clampToGround: false
                    };
                    _polygonEntity.name = 'planeSelf';

                    _polygonEntity._id = id;
                    polyObj = this.map3d.entities.add(_polygonEntity);
                }
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        // mouse
        handler.setInputAction((movement) => {
            let cartesian = this.map3d.camera.pickEllipsoid(movement.endPosition, this.map3d.scene.globe.ellipsoid);
            let cartographic = Cesium.Cartographic.fromCartesian(
                cartesian,
                this.map3d.scene.globe.ellipsoid,
                new Cesium.Cartographic()
            );
            let lng = Cesium.Math.toDegrees(cartographic.longitude);
            let lat = Cesium.Math.toDegrees(cartographic.latitude);

            if (positions.length >= 0) {
                if (cartesian && cartesian.x) {
                    positions.pop();
                    positions.push(cartesian);
                    polygon.positions.pop();
                    polygon.positions.push(cartesian);
                    codeInfo.pop();
                    codeInfo.push([lng, lat]);
                    codeArrInfo.pop();
                    codeArrInfo.pop();
                    codeArrInfo.push(lng);
                    codeArrInfo.push(lat);
                }
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        // right
        handler.setInputAction((movement) => {
            console.log(codeInfo);
            handler.destroy();
            positions.push(positions[0]);
            console.log(codeArrInfo);
            sucess(codeArrInfo);
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    };

    dmgis.cesiummap.Tools.prototype.ContainsPoint = function (polygon, pointX, pointY) {
        let n = polygon.length >> 1;

        let ax, lup;
        let ay = polygon[2 * n - 3] - pointY;
        let bx = polygon[2 * n - 2] - pointX;
        let by = polygon[2 * n - 1] - pointY;

        if (bx === 0 && by === 0) return false; // point on edge

        // let lup = by > ay;
        for (let ii = 0; ii < n; ii++) {
            ax = bx;
            ay = by;
            bx = polygon[2 * ii] - pointX;
            by = polygon[2 * ii + 1] - pointY;
            if (bx === 0 && by === 0) return false; // point on edge
            if (ay === by) continue;
            lup = by > ay;
        }

        let depth = 0;
        for (let i = 0; i < n; i++) {
            ax = bx;
            ay = by;
            bx = polygon[2 * i] - pointX;
            by = polygon[2 * i + 1] - pointY;
            if (ay < 0 && by < 0) continue; // both 'up' or both 'down'
            if (ay > 0 && by > 0) continue; // both 'up' or both 'down'
            if (ax < 0 && bx < 0) continue; // both points on the left

            if (ay === by && Math.min(ax, bx) < 0) return true;
            if (ay === by) continue;

            let lx = ax + ((bx - ax) * -ay) / (by - ay);
            if (lx === 0) return false; // point on edge
            if (lx > 0) depth++;
            if (ay === 0 && lup && by > ay) depth--; // hit vertex, both up
            if (ay === 0 && !lup && by < ay) depth--; // hit vertex, both down
            lup = by > ay;
        }
        return (depth & 1) === 1;
    };

    dmgis.cesiummap.Tools.prototype.pointInRect = function (rect, pointX, pointY) {
        let a = (rect[0] - rect[0]) * (pointY - rect[1]) - (rect[3] - rect[1]) * (pointX - rect[0]);
        let b = (rect[2] - rect[0]) * (pointY - rect[3]) - (rect[3] - rect[3]) * (pointX - rect[0]);
        let c = (rect[2] - rect[2]) * (pointY - rect[3]) - (rect[1] - rect[3]) * (pointX - rect[2]);
        let d = (rect[0] - rect[2]) * (pointY - rect[1]) - (rect[1] - rect[1]) * (pointX - rect[2]);
        return (a > 0 && b > 0 && c > 0 && d > 0) || (a < 0 && b < 0 && c < 0 && d < 0);
    };

    /**************************以下为坐标转换****************************/
    // GASProjection.Gauss_to_XY = function (L, B, middleL2) {
    //     var t = 0,
    //         yita = 0;
    //     var nn = 0;
    //     var n = 0;
    //     var middleL = GASProjection.to_Radian(middleL2);
    //     B = GASProjection.to_Radian(B);
    //     L = GASProjection.to_Radian(L);
    //     var dL = L - middleL;
    //     var cosB = Math.cos(B);
    //     n = to_N(B);
    //     nn = n * Math.cos(B);
    //     t = Math.tan(B);
    //     yita = e2 * cosB;
    //     var pow_t2 = Math.pow(t, 2);
    //     var pow_t4 = Math.pow(t, 4);
    //     var pow_yita2 = Math.pow(yita, 2);
    //     var pow_yita4 = Math.pow(yita, 4);
    //     var pow_cosB3 = Math.pow(cosB, 3);
    //     var pow_cosB5 = Math.pow(cosB, 5);
    //     var tY =
    //         to_Sm(B) +
    //         (Math.pow(dL, 2) / 2) * nn * cosB * t +
    //         (Math.pow(dL, 4) / 24) * t * nn * pow_cosB3 * (5.0 - pow_t2 + 9.0 * pow_yita2 + 4 * pow_yita4) +
    //         (Math.pow(dL, 6) / 720) *
    //             t *
    //             nn *
    //             pow_cosB5 *
    //             (61.0 - 58.0 * t * t + pow_t4 + 270 * pow_yita2 - 330 * t * t * pow_yita2);
    //     var tX =
    //         dL * n * cosB +
    //         (Math.pow(dL, 3) / 6.0) * n * pow_cosB3 * (1 - t * t + yita * yita) +
    //         (Math.pow(dL, 5) / 120.0) *
    //             n *
    //             pow_cosB5 *
    //             (5 - 18 * t * t + pow_t4 + 14.0 * pow_yita2 - 58.0 * pow_yita2 * pow_t2);
    //     return new Cesium.Cartesian2(tX, tY);
    // };
    GASProjection.to_Radian = function (degree) {
        return (degree * Math.PI) / 180.0;
    };
    GASProjection.to_Sm = function (B) {
        var AA, BB, CC, DD, EE;
        AA =
            1 +
            (GASProjection.e1 * GASProjection.e1 * 3) / 4 +
            (Math.pow(GASProjection.e1, 4.0) * 45) / 64 +
            (Math.pow(GASProjection.e1, 6) * 175) / 256 +
            (Math.pow(GASProjection.e1, 8) * 11025) / 16384;
        BB =
            (Math.pow(GASProjection.e1, 2) * 3) / 4 +
            (Math.pow(GASProjection.e1, 4) * 15) / 16 +
            (Math.pow(GASProjection.e1, 6) * 525) / 512 +
            (Math.pow(GASProjection.e1, 8) * 2205) / 2048;
        CC =
            (Math.pow(GASProjection.e1, 4) * 15) / 64 +
            (Math.pow(GASProjection.e1, 6) * 105) / 256 +
            (Math.pow(GASProjection.e1, 8) * 2205) / 4096;
        DD = (Math.pow(GASProjection.e1, 6) * 35) / 512 + (Math.pow(GASProjection.e1, 8) * 315) / 2048;
        EE = (Math.pow(GASProjection.e1, 8) * 315) / 16384;
        return (
            GASProjection.aEarth *
            (1 - GASProjection.e1 * GASProjection.e1) *
            (AA * B -
                (BB / 2) * Math.sin(2 * B) +
                (CC / 4) * Math.sin(4 * B) -
                (DD / 6) * Math.sin(6 * B) +
                (EE / 8) * Math.sin(8 * B))
        );
    };
    GASProjection.to_N = function (B) {
        var ans =
            GASProjection.aEarth / Math.sqrt(1.0 - GASProjection.e1 * GASProjection.e1 * Math.sin(B) * Math.sin(B));
        return ans;
    };
    GASProjection.Gauss_to_XY = function (L, B, middleL2) {
        var t = 0,
            yita = 0;
        var nn = 0;
        var n = 0;
        var middleL = GASProjection.to_Radian(middleL2);
        B = GASProjection.to_Radian(B);
        L = GASProjection.to_Radian(L);
        var dL = L - middleL;
        var cosB = Math.cos(B);
        n = GASProjection.to_N(B);
        nn = n * Math.cos(B);
        t = Math.tan(B);
        yita = GASProjection.e2 * cosB;
        var pow_t2 = Math.pow(t, 2);
        var pow_t4 = Math.pow(t, 4);
        var pow_yita2 = Math.pow(yita, 2);
        var pow_yita4 = Math.pow(yita, 4);
        var pow_cosB3 = Math.pow(cosB, 3);
        var pow_cosB5 = Math.pow(cosB, 5);
        var tY =
            GASProjection.to_Sm(B) +
            (Math.pow(dL, 2) / 2) * nn * cosB * t +
            (Math.pow(dL, 4) / 24) * t * nn * pow_cosB3 * (5.0 - pow_t2 + 9.0 * pow_yita2 + 4 * pow_yita4) +
            (Math.pow(dL, 6) / 720) *
                t *
                nn *
                pow_cosB5 *
                (61.0 - 58.0 * t * t + pow_t4 + 270 * pow_yita2 - 330 * t * t * pow_yita2);
        var tX =
            dL * n * cosB +
            (Math.pow(dL, 3) / 6.0) * n * pow_cosB3 * (1 - t * t + yita * yita) +
            (Math.pow(dL, 5) / 120.0) *
                n *
                pow_cosB5 *
                (5 - 18 * t * t + pow_t4 + 14.0 * pow_yita2 - 58.0 * pow_yita2 * pow_t2);
        return new Cesium.Cartesian2(tX, tY);
    };
    GASProjection.Sm_to_B = function (Sm) {
        var B;
        var B2, B4, B6, B8, fai;
        var AA, BB, CC, DD, EE;
        var A2, A4, A6, A8;
        AA =
            1 +
            (GASProjection.e1 * GASProjection.e1 * 3) / 4 +
            (Math.pow(GASProjection.e1, 4.0) * 45) / 64 +
            (Math.pow(GASProjection.e1, 6) * 175) / 256 +
            (Math.pow(GASProjection.e1, 8) * 11025) / 16384;
        BB =
            (Math.pow(GASProjection.e1, 2) * 3) / 4 +
            (Math.pow(GASProjection.e1, 4) * 15) / 16 +
            (Math.pow(GASProjection.e1, 6) * 525) / 512 +
            (Math.pow(GASProjection.e1, 8) * 2205) / 2048;
        CC =
            (Math.pow(GASProjection.e1, 4) * 15) / 64 +
            (Math.pow(GASProjection.e1, 6) * 105) / 256 +
            (Math.pow(GASProjection.e1, 8) * 2205) / 4096;
        DD = (Math.pow(GASProjection.e1, 6) * 35) / 512 + (Math.pow(GASProjection.e1, 8) * 315) / 2048;
        EE = (Math.pow(GASProjection.e1, 8) * 315) / 16384;
        fai = Sm / (GASProjection.aEarth * (1 - GASProjection.e1 * GASProjection.e1) * AA);
        A2 = BB / AA / 2;
        A4 = -CC / AA / 4;
        A6 = DD / AA / 6;
        A8 = -EE / AA / 8;
        B2 =
            A2 -
            A2 * A4 -
            A4 * A6 -
            0.5 * Math.pow(A2, 3) -
            A2 * Math.pow(A4, 2) +
            0.5 * Math.pow(A2, 2) * A6 -
            18.3 * Math.pow(A2, 3) * A4;
        B4 = A4 + Math.pow(A2, 2) - A2 * A6 * 2 - 4 * A2 * A2 * A4 - 1.3 * Math.pow(A2, 4);
        B6 =
            A6 +
            3 * A2 * A4 -
            3 * A2 * A8 +
            1.5 * Math.pow(A2, 3) -
            4.5 * A2 * A4 * A4 -
            9 * A2 * A2 * A6 -
            12.5 * Math.pow(A2, 3) * A4;
        B8 = A8 + 2 * A4 * A4 + 4 * A2 * A6 + 8 * A2 * A2 * A4 + 2.7 * Math.pow(A2, 4);
        B = fai + B2 * Math.sin(2 * fai) + B4 * Math.sin(4 * fai) + B6 * Math.sin(6 * fai) + B8 * Math.sin(8 * fai);
        return B;
    };
    GASProjection.Gauss_to_BL = function (x, y, m_fL0) {
        var bf;
        var n, t, yita;
        bf = GASProjection.Sm_to_B(y);
        n = GASProjection.to_N(bf);
        t = Math.tan(bf);
        yita = GASProjection.e2 * Math.cos(bf);
        var B =
            bf +
            (t * (-1 - yita * yita) * x * x) / (2.0 * Math.pow(n, 2)) +
            (t *
                (5 +
                    3 * Math.pow(t, 2) +
                    6.0 * Math.pow(yita, 2) -
                    6.0 * Math.pow(t, 2) * Math.pow(yita, 2) -
                    3.0 * Math.pow(yita, 4) -
                    9.0 * Math.pow(t, 2) * Math.pow(yita, 4)) *
                Math.pow(x, 4)) /
                (24.0 * Math.pow(n, 4)) +
            (t *
                (-61.0 -
                    90.0 * Math.pow(t, 2) -
                    45.0 * Math.pow(t, 4) -
                    107 * Math.pow(yita, 2) +
                    162 * Math.pow(t, 2) * Math.pow(yita, 2) +
                    45 * Math.pow(t, 4) * Math.pow(yita, 2)) *
                Math.pow(x, 6)) /
                (720.0 * Math.pow(n, 6));
        var L =
            x / (n * Math.cos(bf)) +
            ((-1 - 2 * Math.pow(t, 2) - Math.pow(yita, 2)) * Math.pow(x, 3)) / (6 * Math.pow(n, 3) * Math.cos(bf)) +
            ((5 +
                28 * Math.pow(t, 2) +
                24 * Math.pow(t, 4) +
                6 * Math.pow(yita, 2) +
                8 * Math.pow(t, 2) * Math.pow(yita, 2)) *
                Math.pow(x, 5)) /
                (120 * Math.pow(n, 5) * Math.cos(bf));
        return new Cesium.Cartographic(L + m_fL0, (B / Math.PI) * 180);
    };
    GASProjection.to_Degree = function (radian) {
        return (radian / Math.PI) * 180.0;
    };
    GASProjection.aEarth = 6378137;
    GASProjection.bEarth = 6356752.3142;
    GASProjection.e1 =
        Math.sqrt(GASProjection.aEarth * GASProjection.aEarth - GASProjection.bEarth * GASProjection.bEarth) /
        GASProjection.aEarth;
    GASProjection.e2 =
        Math.sqrt(GASProjection.aEarth * GASProjection.aEarth - GASProjection.bEarth * GASProjection.bEarth) /
        GASProjection.bEarth;

    function GASProjection() {}
})(dmgis);

//xml转对象
function parseXMLToObjectArray(xmlString) {
    // 创建一个 DOMParser 实例
    const parser = new DOMParser();
    // 将 XML 字符串解析为 DOM 文档
    const xmlDoc = parser.parseFromString(xmlString, 'application/xml');

    // 检查是否有解析错误
    const parserError = xmlDoc.getElementsByTagName('parsererror');
    if (parserError.length > 0) {
        throw new Error('XML 解析错误');
    }

    // 递归函数，用于将 XML 节点转换为对象
    function nodeToObject(node) {
        const result = {};
        if (node.nodeType === Node.ELEMENT_NODE) {
            // 获取节点的属性
            const attrs = node.attributes;
            for (let i = 0; i < attrs.length; i++) {
                const attr = attrs.item(i);
                result[attr.name] = attr.value;
            }

            // 获取子节点
            const children = node.childNodes;
            for (let i = 0; i < children.length; i++) {
                const child = children.item(i);
                if (child.nodeType === Node.ELEMENT_NODE) {
                    const childName = child.nodeName;
                    if (childName in result) {
                        // 如果已经有同名属性，将其转换为数组
                        if (!Array.isArray(result[childName])) {
                            result[childName] = [result[childName]];
                        }
                        result[childName].push(nodeToObject(child));
                    } else {
                        result[childName] = nodeToObject(child);
                    }
                }
            }
        } else if (node.nodeType === Node.TEXT_NODE) {
            result.value = node.nodeValue.trim();
        }
        return result;
    }

    // 获取 DMGISXML 标签内的内容
    const dmgisXmlNode = xmlDoc.getElementsByTagName('DMGISXML')[0];
    if (!dmgisXmlNode) {
        throw new Error('未找到 DMGISXML 标签');
    }

    return nodeToObject(dmgisXmlNode);
}

let data = {
    name: 'DMGISXML',
    version: '1.1',
    children: {
        name: 'REQUEST',
        children: {
            name: 'GET_FEATURES',
            attributes: {
                attributes: '1',
                beginrecord: '0',
                envelope: '1',
                featurelimit: '1000',
                geometry: '1',
                globalenvelope: '1',
                layername: '省界_region',
                nodflag: '0'
            },
            children: {
                name: 'GETOBJ',
                type: '0',
                children: {
                    name: 'SPATIALQUERY',
                    children: {
                        name: 'QUERY',
                        singleLabel: true
                    }
                }
            }
        }
    }
};
// 示例对象
const exampleObjectWithArray = {
    name: 'ROOT',
    children: [
        {
            name: 'ITEM',
            attributes: {
                id: '1',
                type: 'A'
            },
            children: {
                name: 'DETAIL',
                children: {
                    name: 'NAME',
                    singleLabel: true,
                    value: 'Item 1'
                }
            }
        },
        {
            name: 'ITEM',
            attributes: {
                id: '2',
                type: 'B'
            },
            children: {
                name: 'DETAIL',
                children: {
                    name: 'NAME',
                    singleLabel: true,
                    value: 'Item 2'
                }
            }
        }
    ]
};

//对象转xml
function objectToXML(obj) {
    let xml = [];

    function buildXML(node) {
        const name = node.name;
        let attributes;
        if (node.attributes) {
            attributes = Object.entries(node.attributes)
                .map(([key, value]) => `${key}="${value}"`)
                .join(' ');
        } else {
            attributes = '';
        }
        // let attributes = node.attributes
        //     ? Object.entries(node.attributes)
        //           .map(([key, value]) => `${key}="${value}"`)
        //           .join(' ')
        //     : '';
        const value = node.value ? `${node.value}` : '';

        if (node.singleLabel) {
            // 单标签，自闭合
            xml.push(`<${name} ${attributes} ${value ? `value="${value}"` : ''} />`);
        } else {
            // 非单标签，开始标签
            xml.push(`<${name} ${attributes}>${value}`);
            if (node.children) {
                if (typeof node.children === 'object' && !Array.isArray(node.children)) {
                    buildXML(node.children);
                } else if (Array.isArray(node.children)) {
                    node.children.forEach((child) => buildXML(child));
                }
            }
            // 结束标签
            xml.push(`</${name}>`);
        }
    }

    buildXML(obj);
    return xml.join('');
}
// console.log(objectToXML(exampleObjectWithArray));
// console.log(objectToXML(data));

export default dmgis;
